Getting stuck in an array loop, swapping them to children order
<p>Getting a bit lost with the following code, I have an array of values that themselves are arrays, each array consists of a Page_Id, ParentPage_Id and Page (name), I'm trying to loop through the array to rebuild it in order of the ParentPage_Id value, so that the Page_Id 9 would be first, then the next would be 5 because that has the Parent of 9, then 6 because of the parent of 5, then 7, 2, 8 and so on.</p>

<p>Basically need to re-order the original array based on the order of the ParentPage_Id and the children of that if that makes sense.</p>

<p>Any help or pointers would be great, here's my code so far.</p>

<pre><code>$array = array();
array_push($array, array('Page_Id'=&gt;9, 'ParentPage_Id'=&gt;0, 'Page'=&gt;'Page1'));
array_push($array, array('Page_Id'=&gt;4, 'ParentPage_Id'=&gt;0, 'Page'=&gt;'Page2'));
array_push($array, array('Page_Id'=&gt;3, 'ParentPage_Id'=&gt;4, 'Page'=&gt;'Page3'));
array_push($array, array('Page_Id'=&gt;5, 'ParentPage_Id'=&gt;9, 'Page'=&gt;'Page4'));
array_push($array, array('Page_Id'=&gt;11, 'ParentPage_Id'=&gt;3, 'Page'=&gt;'Page5'));
array_push($array, array('Page_Id'=&gt;12, 'ParentPage_Id'=&gt;3, 'Page'=&gt;'Page6'));  
array_push($array, array('Page_Id'=&gt;13, 'ParentPage_Id'=&gt;3, 'Page'=&gt;'Page7'));  
array_push($array, array('Page_Id'=&gt;6, 'ParentPage_Id'=&gt;5, 'Page'=&gt;'Page8'));
array_push($array, array('Page_Id'=&gt;10, 'ParentPage_Id'=&gt;3, 'Page'=&gt;'Page9'));
array_push($array, array('Page_Id'=&gt;7, 'ParentPage_Id'=&gt;6, 'Page'=&gt;'Page10'));
array_push($array, array('Page_Id'=&gt;2, 'ParentPage_Id'=&gt;7, 'Page'=&gt;'Page11'));
array_push($array, array('Page_Id'=&gt;8, 'ParentPage_Id'=&gt;7, 'Page'=&gt;'Page12'));

echo("&lt;pre&gt;");
var_dump(sort_pages($array));

function sort_pages($array) {

$tmp_array = array();

foreach($array as $page) {
    array_push($tmp_array, $page);
    child_pages($array, $page['Page_Id'], 1, $tmp_array);
}

return $tmp_array;

}



function child_pages($param_array, $page_id, $level, &amp;$tmp_array) {

$aPages = array();
foreach($param_array as $aPage) { 
    if(isset($aPage['ParentPage_Id']) &amp;&amp; $aPage['ParentPage_Id'] == $page_id) {
        array_push($aPages, $aPage);
    }
}

foreach($aPages as &amp;$page) {
    array_push($tmp_array, $page);
    child_pages($array, $page['Page_Id'], $level, $tmp_array);
}

return $tmp_array;

}
</code></pre>
