For the past couple of hours, I've been unsuccessfully trying to figure out the php code to display a list in three columns so that it has this order
A D G
B E H
C F I
but I'm really lost. Can anyone help me with this? I currently only have code that lists in this order
A B C
D E F
G H I
This is my current code:
echo '<table><tr>';
foreach ($categories as $k => $category) {
if ($k % 3 == 0 && $k ! = 0) {
echo '</tr><tr>';
}
echo '<td><a href="category.php?category='.$category["id"].'">'.$category["category"].'</a></td>';
}
echo '</table>';
Try this:
$columns = 3;
$rows = ceil(count($categories) / $columns);
echo '<table>';
for ($row = 0; $row < $rows; $row++) {
echo '<tr>';
foreach ($categories as $k => $category) {
if ($k % $rows == $row) {
echo '<td><a href="category.php?category='.$category["id"].'">'.$category["category"].'</a></td>';
}
}
echo '</tr>';
}
echo '</table>';
It's not very efficient, but right now I can't think on a better way of doing it.
If you want to have the list rendered in columns as indicated, you could generate it in the logical order and just uses the CSS columns
property to set in columns:
ul {
-moz-column-count: 2;
-webkit-column-count: 2;
column-count: 2;
}
The bad news is that this is not supported by IE 9 and earlier, but the Columns polyfills like css3-multi-column.js might work sufficiently well in simple cases (despite their limitations and issues).
I had this same issue, and I am posting my answer to this old question for the following reasons:
Some things to note:
Here is my full answer:
function sortVertically( $data = array() )
{
/* PREPARE data for printing */
ksort( $data ); // Sort array by key.
$numCols = 3; // Desired number of columns
$numCells = is_array($data) ? count($data) : 1 ;
$numRows = ceil($numCells / $numCols);
$extraCells = $numCells % $numCols; // Store num of tbody's with extra cell
$i = 0; // iterator
$cCell = 0; // num of Cells printed
$output = NULL; // initialize
/* START table printing */
$output .= '<div>';
$output .= '<table>';
foreach( $data as $key => $value )
{
if( $i % $numRows === 0 ) // Start a new tbody
{
if( $i !== 0 ) // Close prev tbody
{
$extraCells--;
if ($extraCells === 0 )
{
$numRows--; // No more tbody's with an extra cell
$extraCells--; // Avoid re-reducing numRows
}
$output .= '</tbody>';
}
$output .= '<tbody style="float: left;">';
$i = 0; // Reset iterator to 0
}
$output .= '<tr>';
$output .= '<th>'.$key.'</th>';
$output .= '<td>'.$value.'</td>';
$output .= '</tr>';
$cCell++; // increase cells printed count
if($cCell == $numCells){ // last cell, close tbody
$output .= '</tbody>';
}
$i++;
}
$output .= '</table>';
$output .= '</div>';
return $output;
}
I hope you find this answer useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With