denimen denimen - 9 days ago 6
PHP Question

PHP Sorting files in a table

Currently I have a table order by

A B C D

E F G H


but I would like to order the table by

A E

B F

C G

D H


Code:

for($i=0;$i<=count($aFiles);$i++)
{
if($i%5==0)
{
echo "</tr><tr>";
}

echo '<td><a>'.$aFiles[$i].'</a></td>';
}
echo '</tr>';
echo '</table>';


Files are already sorted a-z in
$aFiles
.

Answer

$aFiles = array('a','b','c','d', 'e', 'f', 'g');



$iColumnNumber = 2;
$iRowMaxNumber = ceil(count($aFiles) / $iColumnNumber);

$iTableRow = 0;
$iTableColumns = 1;
$aTableRows = array();

// make array with table cells
foreach ($aFiles as $sFile)
{
    if ($iTableRow == $iRowMaxNumber)
    {
        $iTableRow = 0;
        $iTableColumns++;
    }

    if (!isset($aTableRows[$iTableRow]))
    {
        $aTableRows[$iTableRow] = array();
    }

    $aTableRows[$iTableRow][] = '<td>' . $sFile . '</td>';

    $iTableRow++;
}

// if there is odd number of elements
// we should add empty td elements
for ($iTableRow; $iTableRow < $iRowMaxNumber; $iTableRow++)
{
    if (count($aTableRows[$iTableRow]) < $iTableColumns)
    {
        $aTableRows[$iTableRow][] ='<td>empty</td>';
    }
}

// display table
echo '<table>';

foreach ($aTableRows as $aTableRow)
{

    echo '<tr>';
    echo implode('', $aTableRow);
    echo '</tr>';
}

echo '</table>';