*}
codea teams

Sort An Array In Columns



This function will sort an array in columns. The best way I can explain this is by examples. Supposed I have the following arrays:

{1,2,3,4,5,6,7,8,9}
{1,2,3,4,5,6,7,8,9,10}
{1,2,3,4,5,6,7,8,9,10,11}

I would like to easily print the tables like this:

147
258
369
158
269
3710
4  
159
2610
3711
48 

In order to loop through an array, printing each row, I would like the arrays to be sorted like this

{1,4,7,2,5,8,3,6,9}
{1,5,8,2,6,9,3,7,10,4, , }
{1,5,9,2,6,10,3,7,11,4,8, }

function ArrayColumnSort($data, $nbrColumns = 2, $strForEmptyCell = "-")
{
    $total_count = sizeof($data);
    if ($total_count <= 0)
        return;

    if ($nbrColumns <= 0)
        return;

    $total_rows = ceil($total_count / $nbrColumns);
    $rem = $total_count % $nbrColumns;

    $outArray = array();

    if ($rem > 0) {
        $total_count = $nbrColumns * $total_rows;
    }

    $col = 0;
    $row = 0;
    for($x = 0; $x < $total_count; $x++)
    {
        $pos = ($row) + ($col * $total_rows);

        if ($rem > 0) {
            if ($col > $rem) {
                $pos = $pos - ($col - $rem);
            }

            if ($row == $total_rows - 1) {
                if ($col >= $rem) {
                    $outArray[] = $strForEmptyCell;
                }
                else {
                    $outArray[] = $data[$pos];
                }
            }
            else {
                $outArray[] = $data[$pos];
            }
        }
        else {
            $outArray[] = $data[$pos];
        }
        $col++;

        if ($col == $nbrColumns)
        {
            $col = 0;
            $row ++;
        }

    }

    return $outArray;
}

To use the array in smarty templates

<table border='1'>
    {section name=main loop=$test_arr step=$columns}
        <tr>
            {section name=mycol loop=$columns step=1}
            {assign var=myindex value=`$smarty.section.main.index+$smarty.section.mycol.index`}
            <td style='padding:10px'>{$test_arr[$myindex]}</td>
            {/section}

        </tr>
    {/section}
</table>

To print the array using php

echo "<table border='1' cellpadding='2' cellspacing='2'>";
for($x = 0; $x < sizeof($dispArr); $x = $x + $columns) {
    echo "<tr>";
    for ($y = 0; $y < $columns; $y++) {
        echo "<td>" . $dispArr[$x + $y] . "</td>";
    }
    echo "</tr>";
}
echo "</table>";