lundi 1 août 2016

How to chunk results into 3 columns

I have a set of results (e.g. [1,2,3,4,5,6,7,8,9,10,11]).

Which I want to be displayed as 1 row with 3 columns

1|5|9
2|6|10
3|7|11
4|8|

What I get is 1 row with 4 columns

1|4|7
2|5|8
3|6|9

10|
11|

Until I add a 12th object then I get 1 row with 3 columns

1|5|9
2|6|10
3|7|11
4|8|12

My code in blade template

<!-- partials/tables/table_list.blade.php -->

@section('tables')
<?php $chunkSize = floor(count($tables) / 3); ?>
<section id="tables-overview">
    <div class="row">
        @foreach ($tables->chunk($chunkSize , 1) as $chunk)
        <div class="col-md-4">
            @include('partials.tables.table_chunk')
        </div>
        @endforeach
    </div>
</section>
@endsection

<!-- partials/tables/table_chunk.blade.php -->

<table class="table table-responsive">
<thead>
    <tr>
        <th class="text-center">@lang('table.identifier')</th>
        <th class="text-center">@lang('table.property')</th>
        <th class="text-center">
            @permission('manage-tables')
                <a href="">@lang('action.create')</a>
            @endpermission
        </th>
    </tr>
</thead>
<tbody>
    @foreach ($chunk as $table)
    <tr>
        <td class="text-center"></td>
        <td class="text-center"></td>
        <td class="text-center">
            @permission('manage-tables')
                <a class="btn btn-primary" href="">@lang('action.update')</a>
            @endpermission
        </td>
    </tr>
    @endforeach

</tbody>
</table>

When the number of $tables can be divided by 3 (number of columns I want) I get 3 chunks. If not I get 3 chunks + the remaining 1 or 2 objects which both get put in a 4th column. I can place them horizontally as done here but I find this to be 'odd'. When reading a list you read from top to bottom first and then left to right.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire