title: PHP category tree recursion
body: <p>I need to build a table of categories by recursion through an array. It works fine as long as the depth goes deeper but as soon as the depth decreases the HTML output misses the start of a table.</p>
  
  <p>PHP code to build the array:</p>
  
  <pre><code>       if($query-&gt;rowCount() &gt; 0) {
          while($result = $query-&gt;fetch(PDO::FETCH_OBJ)) {
              $tree[] = $result;
          }
          $childs = array();
  
          foreach($tree as $item) {
              $childs[$item-&gt;parent_id][] = $item;
          }
  
  
          foreach($tree as $item) {
              if (isset($childs[$item-&gt;id])) {
                 $item-&gt;childs = $childs[$item-&gt;id];
              }
          }
  
          $tree = $childs[0];
      }
      else {
          // no category blabla
      }
  </code></pre>
  
  <p>Here is the function to build the table. It fails to work correctly.</p>
  
  <pre><code>    function draw($tree) {
      echo "&lt;table border='1' width='300'&gt;";
      echo "&lt;tr&gt;";
      echo "&lt;td&gt;Name&lt;/td&gt;&lt;td&gt;Depth&lt;/td&gt;&lt;td&gt;Parent&lt;/td&gt;";
      echo "&lt;/tr&gt;";
      foreach($tree as $key =&gt; $value) {
          echo "&lt;tr&gt;";
          echo "&lt;td&gt;".$value-&gt;name."&lt;/td&gt;";
          echo "&lt;td&gt;".$value-&gt;depth."&lt;/td&gt;";
          echo "&lt;td&gt;".$value-&gt;parent_id."&lt;/td&gt;";
          echo "&lt;/tr&gt;";
          if(isset($value-&gt;childs)) {
              draw($value-&gt;childs);
          }
      }
      echo "&lt;/table&gt;";
  
  }
  </code></pre>
  
  <p>As requested the HTML Output snippet:</p>
  
  <pre><code>&lt;table border='1' width='300'&gt;
      &lt;tr&gt;
          &lt;td&gt;Name&lt;/td&gt;
          &lt;td&gt;Depth&lt;/td&gt;
          &lt;td&gt;Parent&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Bad&lt;/td&gt;
          &lt;td&gt;5&lt;/td&gt;
          &lt;td&gt;5&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Good&lt;/td&gt;
          &lt;td&gt;5&lt;/td&gt;
          &lt;td&gt;5&lt;/td&gt;
      &lt;/tr&gt;
  &lt;/table&gt;
      &lt;!--- BREAK HAPPENS HERE-----&gt;
      &lt;tr&gt;
          &lt;td&gt;Both?&lt;/td&gt;
          &lt;td&gt;4&lt;/td&gt;
          &lt;td&gt;3&lt;/td&gt;
      &lt;/tr&gt;
      &lt;table border='1' width='300'&gt;
          &lt;tr&gt;
              &lt;td&gt;Name&lt;/td&gt;
              &lt;td&gt;Depth&lt;/td&gt;
              &lt;td&gt;Parent&lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr&gt;
              &lt;td&gt;dsadas&lt;/td&gt;
              &lt;td&gt;5&lt;/td&gt;
              &lt;td&gt;16&lt;/td&gt;
          &lt;/tr&gt;
      &lt;/table&gt;
  </code></pre>