Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is not necessarily a job for recursion, this can be done easily by iteration.</p> <pre><code>&lt;?php $data = array( array('id' =&gt; 1001, 'ParentId' =&gt; NULL, 'Name' =&gt; 'Computing', 'Level' =&gt; 0), array('id' =&gt; 1002, 'ParentId' =&gt; NULL, 'Name' =&gt; 'Cassettes &amp; Vinyl', 'Level' =&gt; 0), array('id' =&gt; 1003, 'ParentId' =&gt; 1001, 'Name' =&gt; 'CD Players', 'Level' =&gt; 1), array('id' =&gt; 1004, 'ParentId' =&gt; 1002, 'Name' =&gt; 'CD Writers', 'Level' =&gt; 1), array('id' =&gt; 1005, 'ParentId' =&gt; 1003, 'Name' =&gt; 'CD-ROM Drives', 'Level' =&gt; 2), array('id' =&gt; 1006, 'ParentId' =&gt; 1004, 'Name' =&gt; 'Computing', 'Level' =&gt; 3) ); $index = array(); $tree = array(); // step 1: build index (note that I use &amp;$row references!) foreach ($data as &amp;$row) { $index[$row['id']] = &amp;$row; $row['children'] = array(); if ($row['ParentId'] == NULL) { $tree[] = &amp;$row; } } // step 2: link tree (references here as well!) foreach ($data as &amp;$row) { $index[$row['ParentId']]['children'][] = &amp;$row; } print_r($tree); ?&gt; </code></pre> <p>result:</p> <pre><code>Array ( [0] =&gt; Array ( [id] =&gt; 1001 [ParentId] =&gt; [Name] =&gt; Computing [Level] =&gt; 0 [children] =&gt; Array ( [0] =&gt; Array ( [id] =&gt; 1003 [ParentId] =&gt; 1001 [Name] =&gt; CD Players [Level] =&gt; 1 [children] =&gt; Array ( [0] =&gt; Array ( [id] =&gt; 1005 [ParentId] =&gt; 1003 [Name] =&gt; CD-ROM Drives [Level] =&gt; 2 [children] =&gt; Array ( ) ) ) ) ) ) [1] =&gt; Array ( [id] =&gt; 1002 [ParentId] =&gt; [Name] =&gt; Cassettes &amp; Vinyl [Level] =&gt; 0 [children] =&gt; Array ( [0] =&gt; Array ( [id] =&gt; 1004 [ParentId] =&gt; 1002 [Name] =&gt; CD Writers [Level] =&gt; 1 [children] =&gt; Array ( [0] =&gt; Array ( [id] =&gt; 1006 [ParentId] =&gt; 1004 [Name] =&gt; Computing [Level] =&gt; 3 [children] =&gt; Array ( ) ) ) ) ) ) ) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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