In Action

Php Multi-Dimensional Array to HTML Table

This example takes a multi-dimensional array and produces an HTML table. This stuff can get a bit dicey. I created a two dimensional array. In terms of this array I created some rules within the inner array. The first element represents the type of fruit/vegetable. The second element is the variety. The remaining items represent the attributes.

Php in Action


forloop



Toycode

Php Code

Just cut-n-paste to reuse.

     
<?php
$fruit_veggies;
$fruit_veggies = array(
           array(
              array("Lettuce","Butter Crunch", "Heirloom", "Green"),
              array("Lettuce", "Bibb",  "Heirloom", "Green"),
              array("Lettuce", "Iceberg", "Heirloom", "Green"),
              array("Lettuce", "Romaine", "Heirloom", "Green")                      
           ),
           array(
                 array("Tomato", "Beefsteak", "Hybrid", "Red"),
                 array("Tomato", "Tiny Tom", "Heirloom", "Red"),
                 array("Tomato", "Amish Paste", "Heirloom", "Red"), 
                 array("Tomato", "Banana Legs", "Heirloom", "Yellow") 
                ),
           array(
                 array("Apple", "Fuji", "", "Red"),
                 array("Apple", "Golden Delicious", "", "Yellow"),
                 array("Apple", "Red Delicious", "", "Red"),
                 array("Apple", "Cameo", "", "Red")
                )
           );

echo '<table border="1" cellspacing="0" width="125">';
for ( $arrnum = 0; $arrnum < 3; $arrnum++ )
{
   
  for ( $row = 0; $row < 4; $row++ ) 
  {
    echo '<tr>';
   
    for ( $col = 0; $col < 4; $col++ )
    {
     if ($fruit_veggies[$arrnum][$row][$col] == '') 
     {
     	echo "<td> </td>";
     }
     else
     {
     	if ($row == 0 and $col == 0)
     	{
     	echo "<td>". $fruit_veggies[$arrnum][$row][$col] . "</td>";
     	}
     	else if ($row != 0 and $col == 0)
     	{
     		echo "<td> </td>";
     	}
     	else
     	{
     	echo "<td>". $fruit_veggies[$arrnum][$row][$col] . "</td>";
     	}			        
     } 
    } 

  }
  echo "</tr>";
}   
echo "</table>";


?>