title: PHP Building Recursive Array from List
body: <p>I am returning a list of pages and their parent pages from a MySQL database and putting all results into an array as follows where every result is an array which includes the parent, name and id of the forum (the key of array pages is also the same as page id). </p>
  
  <p>For the sake of the model and the applicaiton, there are some other parameters. </p>
  
  <ul>
  <li>"root pages" have a parent of 0</li>
  <li>there are no orphaned pages</li>
  </ul>
  
  <p>so, the MySQL query will return this dataset.</p>
  
  <pre><code>pages=&gt;
       [1] =&gt; array(id=&gt;1, 
                    parent=&gt;0, 
                    name=&gt;Hello World)
       [2] =&gt; array(id=&gt;1, 
                    parent=&gt;1, 
                    name=&gt;Child of Hello World)
       [3] =&gt; array(id=&gt;1, 
                    parent=&gt;0, 
                    name=&gt;Brother of Hello World)
       [4] =&gt; array(id=&gt;4, 
                    parent=&gt;2, 
                    name=Grand-child of Hello World)
       [6] =&gt; array(id=&gt;6, 
                    parent=&gt;4, 
                    name=Great-grand-child of Hello World)
  </code></pre>
  
  <p>i would then like to transform the array into something that looks like this</p>
  
  <pre><code>pages=&gt;
       [1] =&gt; id=&gt;1, 
              name=&gt;Hello World
              children=&gt;
  
                  [2] =&gt; id=&gt;1
                         name=&gt;Child of Hello World
                         children=&gt;
  
                             [4] =&gt; 
                               id=&gt;4
                               name=&gt; Grand-child of Hello World)
                               children=&gt;
  
                                   [6] =&gt; 
                                     id=&gt;6
                                     name=&gt; Great-grand-child of Hello World
                                     children= null
  
       [3] =&gt; array(id=&gt;1, 
                    name=&gt;Brother of Hello World
                    children=&gt;null
  </code></pre>
  
  <p>So basically, i want to turn a linear array into a nested multidimensional array so that i can print my sitemap.</p>
  
  <p>it needs to be a recursive solution. there are over 700 pages and up to 5 or 6 levels.</p>
  
  <p>i only want to do 1 mysql query. not 700 so please dont give me a mysql based solution.</p>