Columnize an Array with PHP
January 22, 2011| Tweet |
Download Original
<?PHP function columnize($data,$maxrows=10) { /* Columnize - Robert Lerner - 2011.01.13.21.23 - www.Robert-Lerner.com/columnize.php Use: STRING = columnize(ARRAY[MIXED],INTEGER); Array may not be multidimensional. Sorts array elements into columns, data + <br />. */ { } { } $ColumnID = 0; { if ($DataCount%$maxrows==0) { $ColumnID++; } $Col[$ColumnID] .= $data[$DataCount] . "<br />"; } $RetVal = "<table><tr>"; for ($i=1;$i<=$ColumnID;$i++) { $RetVal .= "<td valign='top'>" . $Col[$i] . "</td>"; } $RetVal .= "</tr></table>"; RETURN $RetVal; }
This example uses the function after generating an array with the following elements:
$arr[0] = 0;
$arr[1] = 1;
etc...
for ($i=0;$i<=49;$i++)
{
$arr[$i] = $i;
}
echo columnize($arr,2);
Output
| 0 1 | 2 3 | 4 5 | 6 7 | 8 9 | 10 11 | 12 13 | 14 15 | 16 17 | 18 19 | 20 21 | 22 23 | 24 25 | 26 27 | 28 29 | 30 31 | 32 33 | 34 35 | 36 37 | 38 39 | 40 41 | 42 43 | 44 45 | 46 47 | 48 49 |
Changing the second parameter of columnize to 5, and then 10 below:
Output
| 0 1 2 3 4 | 5 6 7 8 9 | 10 11 12 13 14 | 15 16 17 18 19 | 20 21 22 23 24 | 25 26 27 28 29 | 30 31 32 33 34 | 35 36 37 38 39 | 40 41 42 43 44 | 45 46 47 48 49 |
| 0 1 2 3 4 5 6 7 8 9 | 10 11 12 13 14 15 16 17 18 19 | 20 21 22 23 24 25 26 27 28 29 | 30 31 32 33 34 35 36 37 38 39 | 40 41 42 43 44 45 46 47 48 49 |

Facebook
LinkedIn