In Action

Php Toycode - Turning a two-dimensional array into an html table - Example #2

This example expands upon the last one. In the last example our array was fixed. But, what if we needed to set the array dimmensions at runtime?

Php in Action


forloop



Toycode

Php Code

Just cut-n-paste to reuse.

     
<?php           
//Example mdimarr1a was well and good if data is either fixed or known at 
//program runtime... but, how would we deal with dynamic data coming back  
//from a query? 

$tblrows = array();
$tblrow = array();
$tblrow[0] = array("A1", "B1" , "C1") ; 
$tblrow[1] = array("A2", "B2" , "C2") ;
$tblrow[2] = array("A3", "B3" , "C3") ;
$tblrows = $tblrow;    
$table = $tblrows;
             
echo "<pre>" .            
'$tblrows = array();
$tblrow = array();
$tblrow[0] = array("A1", "B1" , "C1") ; 
$tblrow[1] = array("A2", "B2" , "C2") ;
$tblrow[2] = array("A3", "B3" , "C3") ;
$tblrows = $tblrow;    
$table = $tblrows;'
              . "</pre><br />" ;
             
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)
	{
		echo "<td>" . $cell . "</td>";
	}	
  echo "</tr></table>";
}	
            
?>