gosulove gosulove - 3 months ago 21
MySQL Question

php display array data in multiple columns by using ceil function

For example, I have a array with 8 data. I want to display in this format

$a = array(1,2,3,4,5,6,7,8);
======
1 2
3 4
5 6
7 8
=====


OR array with 11 data

$a = array(1,2,3,4,5,6,7,8,9,10,11);
=========
1 2 3
4 5 6
7 8 9
10 11
=========


Not sure which part i got wrong. Here is my code

$a = array(1,2,3,4,5,6,7,8);
$c = ceil(count($a)/2);

echo "<table>";
for($i=0; $i<$c;$i++){
echo "<tr>";
echo '<td>'.$a[$i].'</td>';
echo '<td>'.$a[$i+1].'</td>';
}
echo "</table>";


However, my data display in this way instead

======
1 2
2 3
3 4
4 5
=====


Basically, I want to display my data from mysql in this format. But before that, I need to test out the ceil function and see if its working. Anyone knows whats wrong with my coding?

Answer

Since you have 2 cels per row you need to calculate the actual index. Also don't forget to close the <tr>

for($i=0; $i<$c;$i++){
    echo "<tr>";
    echo '<td>'.$a[$i * 2].'</td>';
    echo '<td>'.$a[$i * 2 + 1].'</td>';
    echo '</tr>';
}

Here is a full example of a cleaner solution:

<?php
$a = array(1,2,3,4,5,6,7,8);
$cols = 2;
$c = ceil(count($a) / $cols);

echo "<table>";
for($i = 0; $i < $c; $i++){
    echo "<tr>";
    for ($col = 0; $col < $cols; $col++) {
        $value = isset($a[$i * $cols + $col]) ? $a[$i * $cols + $col] : '';
        echo '<td>'. $value .'</td>';
    }
    echo "</tr>";
}
echo "</table>";
Comments