title: Getting a modified preorder tree traversal model (nested set) into a <ul>
body: <p>I am trying to get my data which is hierarchically set up with a tree traversal model into an &lt; ul> in order to show on my site. </p>
  
  <p>Here is my code:</p>
  
  <pre><code>function getCats($) {
    // retrieve all children of $parent
    $query = "SELECT max(rght) as max from t_categories";
    $row = C_DB::fetchSingleRow($query);
    $max = $row["max"];
    $result ="&lt;ul&gt;";
    $query = "SELECT * from t_categories where lft &gt;=0 and rght &lt;= $max";
    if($rs = C_DB::fetchRecordset($query)){
      $p_right ="";
      $p_left ="";
      $p_diff="";          
      while($row = C_DB::fetchRow($rs)){
        $diff = $row["rght"] -$row["lft"];
  
        if($diff == $p_diff){
          $result.= "&lt;li&gt;".$row['title']."&lt;/li&gt;";
        }elseif (($row["rght"] - $row["lft"] &gt; 1) &amp;&amp; ($row["rght"] &gt; $p_right)){
          $result. "&lt;ul&gt;";
          $result.= "&lt;li&gt;".$row['title']."&lt;/li&gt;";
  
        }else{
          $result.= "&lt;li&gt;".$row['title']."&lt;/li&gt;";
        } 
  
        $p_right = $row["rght"];
        $p_left = $row["lft"];
        $p_diff = $diff;
      }
    }
    $result.= "&lt;/ul&gt;";
    return $result;
  } 
  </code></pre>
  
  <p>Here is my sample table:</p>
  
  <pre><code>|ID  |  TITLE | lft| rght |
  |1   | Cat 1  | 1      |    16       |
  |18  | Cat 2  | 3      |    4       |
  |22  | Cat 3  | 5      |    6       |
  |28  | Cat 4  | 7      |    8       |
  |34  | Cat 5  | 9      |    9       |
  |46  | Cat 6  | 11      |    10       |
  |47  | Cat 7  | 13      |    12       |
  |49  | Cat 8  | 15      |    14       | 
  </code></pre>
  
  <p>Now it outputs something like:</p>
  
  <pre><code>    &lt;ul&gt;
  &lt;li&gt;Cat 1&lt;/li&gt;
  &lt;li&gt;Cat 2&lt;/li&gt;
  &lt;li&gt;Cat 3&lt;/li&gt;
  &lt;li&gt;Cat 4&lt;/li&gt;
  &lt;li&gt;Cat 5&lt;/li&gt;
  &lt;li&gt;Cat 6&lt;/li&gt;
  &lt;li&gt;Cat 7&lt;/li&gt;
  &lt;li&gt;Cat 8&lt;/li&gt;
  &lt;/ul&gt;
  </code></pre>
  
  <p>Can anyone tell me why or how it will output the list in hierarchical a structure?</p>
  
  <p><a href="https://stackoverflow.com/questions/1300567/php-infinite-loop/1300599#1300599">Related topic</a></p>