|
Developer Geek Resources Php Code Examples |
Custom Search
|
This example is coded to allow for the creation of a two dimmensional array at runtime. A while ago I needed to write a cross-tabulation algorithm. One of the items I needed was the ability to generate a 2D array. This is a scaled down example of this. This example keeps building from the previous two.
Just cut-n-paste to reuse.
<?php
$tblcols = createSizedArray(4);
$tblrows = createSizedArray(3);
$numrows = sizeof($tblrows);
for ($n=0;$n<$numrows;$n++)
{
$tblrows[$n] = $tblcols;
}
$table = $tblrows;
echo "get single element <br />";
echo '$table[2][1] = ' . $table[2][1] . "<br />";
echo "or we can access the \$tblrows array directly <br />";
echo '$tblrows[1][2] = ' . $tblrows[1][2] . "<br /><br />";
echo "build html table from a 2d array <br />";
foreach ($table as $rows => $row)
{
echo "<table border='1'><tr>";
foreach ($row as $col => $cell)
{
if ($cell != '')
{
echo "<td width='100'>" . $cell . "</td>";
}
else
{
echo "<td width='100'>" . "zzz" . "</td>";
}
}
echo "</tr></table>";
}
function createSizedArray($sz)
{
$arr = array();
for ($i=0;$i<$sz;$i++)
{
$arr[$i] = '';
}
return $arr;
}
?>
Arrays
Dimensional Arrays
Hash/Associative Array
Regular Expressions
$_SESSION