Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There's another way to achieve the same effect which I find a bit easier to follow (without the reference trick). You build the tree by adding the relevant information to the current node and to its parent (assume the foreach iterates over the returned rows from the SQL query):</p> <pre><code>$tree = array(); foreach ($query-&gt;result() as $row) { $pid = $row-&gt;parent_id; $id = $row-&gt;id; $name = $row-&gt;name; // Create or add child information to the parent node if (isset($tree[$pid])) // a node for the parent exists // add another child id to this parent $tree[$pid]["children"][] = $id; else // create the first child to this parent $tree[$pid] = array("children"=&gt;array($id)); // Create or add name information for current node if (isset($tree[$id])) // a node for the id exists: // set the name of current node $tree[$id]["name"] = $name; else // create the current node and give it a name $tree[$id] = array( "name"=&gt;$name ); } return $tree; </code></pre> <p>and to display the tree:</p> <pre><code>function toUL($tree, $id, $html){ $html .= '&lt;ul&gt;'.PHP_EOL; if (isset($tree[$id]['name'])) $html .= '&lt;li&gt;' . $tree[$id]['name']; if (isset($tree[$id]['children'])) { $arChildren = &amp;$tree[$id]['children']; $len = count($arChildren); for ($i=0; $i&lt;$len; $i++) { $html .= toUL($tree, $arChildren[$i], ""); } $html .= '&lt;/li&gt;'.PHP_EOL; } $html .= '&lt;/ul&gt;'.PHP_EOL; return $html; } // Display the tree echo toUL($tree, 0, ""); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload