Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

echo php foreach loop result in 3 column

Tags:

foreach

php

I have a foreach loop and my code looks this is:

foreach($items as $item){
    echo $item['title'];
}

For example I have 15 items in my loop. My loop will output something like this:

item 1
item 2
item 3
item 4
item 5
item 6
item 7
item 8
item 9
item 10
item 11
item 12
item 13
item 14 
item 15

How can I show my results in 3 columns like the example below in a div or table?

    item 1       item 6      item 11
    item 2       item 7      item 12
    item 3       item 8      item 13
    item 4       item 9      item 14
    item 5       item 10     item 15
like image 487
user3246727 Avatar asked Dec 08 '22 06:12

user3246727


1 Answers

You can use array_chunk to split into the number of groups you desire then use twitter bootstrap to place your items into a div like

<div class="row">
$all_items = array_chunk($my_array,3);

foreach($all_items as $div_item){
foreach ($div_item as $col_md_4_item){
echo '<div class="col-md-4">';
echo $col_md_4_item;
echo '</div>';
}
}
</div>
like image 96
Gandalf Avatar answered Dec 24 '22 10:12

Gandalf