Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You need to implement recursion to make repeated calls to the database to retrieve all children. You will have to replace my database abstraction layer implementation with your own but the concept is the same.</p> <h2><strong>memcache solution</strong></h2> <pre><code>function generateTree($parentid = 0, &amp;$tree) { $sql = sprintf('SELECT * FROM navigation WHERE parentid = %d', $parentid); $res = $this-&gt;db-&gt;results($sql); if ($res) { foreach ($res as $r) { // push found result onto existing tree $tree[$r-&gt;id] = $r; // create placeholder for children $tree[$r-&gt;id]['children'] = array(); // find any children of currently found child $tree = generateTree($r-&gt;id, $tree[$r-&gt;id]['children']); } } } function getTree($parentid) { // memcache implementation $memcache = new Memcache(); $memcache-&gt;connect('localhost', 11211) or die ("Could not connect"); $tree = $memcache-&gt;get('navigation' . $parentid); if ($tree == null) { // need to query for tree $tree = array(); generateTree($parentid, $tree); // store in memcache for an hour $memcache-&gt;set('navigation' . $parentid, $result, 0, 3600); } return $tree; } // get tree with parentid = 0 getTree(0); </code></pre> <h2><strong>non memcache solution</strong></h2> <pre><code>function generateTree($parentid = 0, &amp;$tree) { $sql = sprintf('SELECT * FROM navigation WHERE parentid = %d', $parentid); $res = $this-&gt;db-&gt;results($sql); if ($res) { foreach ($res as $r) { // push found result onto existing tree $tree[$r-&gt;id] = $r; // create placeholder for children $tree[$r-&gt;id]['children'] = array(); // find any children of currently found child $tree = generateTree($r-&gt;id, $tree[$r-&gt;id]['children']); } } } // get tree with parentid = 0 $tree = array(); $parentid = 0; generateTree($parentid, $tree); // output the results of your tree var_dump($tree); die; </code></pre> <p>The above is untested so if anybody catches an error please let me know or feel free to update.</p>
 

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