<html>
<! RecursiveArray.php                                         >
<! Chapter 7, Oracle Database XE PHP Web Programming          >
<! by Michael McLaughlin                                      >
<!                                                            >
<! This script declares an array and demonstrates how to use  >
<! recursion to render an infinite table.                     >
<head>
<title>
  Chapter 7 : RecursiveArray.php
</title>
</head>
<body>
<?php
  // Declare an asymmetrical multidimensional array.
  $tolkien = array
             ("Bilbo"=>array
                ("Hobbit"=>"Who slew a dragon for dwarves."
                ,"Fellowship"=>"Left the ring for Frodo."
                ,"Return of the King"=>array
                    ("Action 1"=>"Destroyed the one ring"
                    ,"Action 2"=>"Left middle earth."))
             ,"Frodo"=>array
                ("Fellowship"=>"Who inherited the ring."
                ,"Return of the King"=>"Who destroyed the ring.")
             ,"Gildor"=>"A high elf met on the road."
             ,"Sam"=>array
                ("Fellowship"=>"An eavesdropper at the windoe."
                ,"Two Towers"=>"A lone companion of Frodo"
                ,"Return of the King"=>"A ring bearer too.")
             );


  // Print the table and nested tables.
  print nested_tables($tolkien);

  // A recursive program for rendering nested tables.
  function nested_tables($array_in)
  {
    // Declare variable with table start.
    $output = "<table border=0 cellpadding=0 cellspacing=0>";

    // Read and add array keys and values to a string.
    foreach ($array_in as $hashName => $hashValue)
    {
      // Append row tag and first column value.
      $output .= "<tr><td valign=top>[".$hashName."]</td>";

      // Check column value for nested array.
      if (is_array($hashValue))
      {
        // Call recursively a copy of itself with cell tags.
        $output .= "<td>".nested_tables($hashValue)."</td></tr>";
      }
      else
      {
        // Append non-array value with cell tags.
        $output .= "<td>[".$hashValue."]</td></tr>";
      }
    }

    // Close HTML table.
    $output .= "</table>";

    // Return the HTML table.
    return $output;
  }
?>
</body>
</html>
