Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break PHP array into 3 columns

I'm trying to break a PHP array into 3 columns (has to be columns, not rows) so it would look something like this:

Item 1     Item 2     Item 3
Item 4     Item 5     Item 6
Item 7     Item 8     Item 9
Item 10................

The best approach I can think of would be to break the main array into 3 arrays, 1 for each column although I can't work out the best approach to do this - more specifically the criteria I could use to generate the 3 arrays.

like image 685
RobM Avatar asked Jan 02 '12 01:01

RobM


2 Answers

$data = array(); 
$columns = 3;

echo "<table><tr>";

for($i = 0; $i < count($data); $i++)
{
 if($i%$columns == 0)
  echo "</tr><tr>";
 echo "<td>".$data[i$]."</td>";
}
echo "</tr></table>";

There you go, it just outputs another row when you get to your column count. You might need to add some logic when the data isnt a multiple of 3.

like image 192
TJHeuvel Avatar answered Sep 21 '22 06:09

TJHeuvel


Using array_chunk you can split array :

$rows = array_chunk($yourArray, '3'); // 3 = column count;
foreach ($rows as $columns) {
    echo "<div class='row'>";
    foreach ($columns as $column) { 
        echo "<div class='column'>$column</div>"; 
    }
    echo "</div>";
}
like image 34
M Rostami Avatar answered Sep 19 '22 06:09

M Rostami