we make a selection of the page data from the database and their parents, sorted by PARENT_ID, PAGE_ID
(ORDER BY PARENT_ID, PAGE_ID)
, we get an array at the beginning of which will be the pages of the first level and by increasing deeper levels. We form an array from it (add additional fields to taste) - an example of the resulting array:
$pages = array ( array('PAGE_ID' => 1, 'PARENT_ID' => 0), array('PAGE_ID' => 2, 'PARENT_ID' => 0), array('PAGE_ID' => 3, 'PARENT_ID' => 1), array('PAGE_ID' => 4, 'PARENT_ID' => 2), array('PAGE_ID' => 5, 'PARENT_ID' => 4), array('PAGE_ID' => 6, 'PARENT_ID' => 5), array('PAGE_ID' => 7, 'PARENT_ID' => 5), array('PAGE_ID' => 8, 'PARENT_ID' => 5) );
let's start the crawl from the pages of a deeper hierarchy, for this we invert the array
$pages = array_reverse($pages);
and go through it pulling out the sub pages and putting them in the correct order in the current array:
foreach ($pages as $k => &$p) { foreach ($pages as &$page){ if($page['PAGE_ID'] == $p['PARENT_ID']){ $page['sub'][] = $p; unset($pages[$k]); continue; } } }
we derive what we got:
print_r($pages);
we see the following construction (a bit long, but which is just not done for clarity :))
Array ( [6] => Array ( [PAGE_ID] => 2 [PARENT_ID] => 0 [sub] => Array ( [0] => Array ( [PAGE_ID] => 4 [PARENT_ID] => 2 [sub] => Array ( [0] => Array ( [PAGE_ID] => 5 [PARENT_ID] => 4 [sub] => Array ( [0] => Array ( [PAGE_ID] => 8 [PARENT_ID] => 5 ) [1] => Array ( [PAGE_ID] => 7 [PARENT_ID] => 5 ) [2] => Array ( [PAGE_ID] => 6 [PARENT_ID] => 5 ) ) ) ) ) ) ) [7] => Array ( [PAGE_ID] => 1 [PARENT_ID] => 0 [sub] => Array ( [0] => Array ( [PAGE_ID] => 3 [PARENT_ID] => 1 ) ) )
those. we have an array with hierarchies, on the basis of which it is possible to implement navigation, sitemap generation, etc.
PS I hope this is what was required.