I am trying to create a nested pages-list from data stored in the MySQL database. I try to do this because users can order the pages (using JS-script nestedSortable) in the way they want and from that array, I can then create a menu with the items in the right order.
My pages have the following data stored:
page_id
parent_page_id
ordering
site_id
title
I retrieve the following from the database:
SELECT * FROM `pages` WHERE site_id = '".$iSite_id."' ORDER BY parent_page_id, ordering ASC;
If a page does not have a parent, the parent_page_id is 0.
So far so good, but I have a lot of problems understanding how a recursive function works, and because the amount of levels is (theoretically) endless, I can't work around creating this function.
This is what I have so far:
$aPagesMenu = $oPage_controller->return_pages_menu($iSite_id);
function create_menu_recursive($aPagesMenu) {
foreach($aPagesMenu as $aPage) {
if($aPage['parent_page_id']){
$aMenu[$aPage['parent_page_id']][$aPage['page_id']] = $aPage['title'];
//Recursive function call here?
} else {
$aMenu[$aPage['page_id']] = $aPage['title'];
}
return $aMenu;
}
$aRecursiveMenu = create_menu_recursive($aPagesMenu);
I get stuck at trying to understand how the recursive function returns its content into the array of the first level? How can I understand this and correctly nest one level into another?
I really wish to understand this, because it gives me a lot of delay and issues. Any help is welcome!
EDIT
Some data retreived from database:
array(6) {
[0]=>
array(4) {
["page_id"]=>
string(3) "274"
["parent_page_id"]=>
string(1) "0"
["menu_ordering"]=>
string(1) "0"
["page_description"]=>
NULL
}
[1]=>
array(4) {
["page_id"]=>
string(3) "278"
["parent_page_id"]=>
string(1) "0"
["menu_ordering"]=>
string(1) "1"
["page_description"]=>
NULL
}
[2]=>
array(4) {
["page_id"]=>
string(3) "273"
["parent_page_id"]=>
string(3) "274"
["menu_ordering"]=>
string(1) "0"
["page_description"]=>
NULL
}
[3]=>
array(4) {
["page_id"]=>
string(3) "275"
["parent_page_id"]=>
string(3) "274"
["menu_ordering"]=>
string(1) "1"
["page_description"]=>
NULL
}
[4]=>
array(4) {
["page_id"]=>
string(3) "276"
["parent_page_id"]=>
string(3) "275"
["menu_ordering"]=>
string(1) "0"
["page_description"]=>
NULL
}
[5]=>
array(4) {
["page_id"]=>
string(3) "277"
["parent_page_id"]=>
string(3) "275"
["menu_ordering"]=>
string(1) "1"
["page_description"]=>
NULL
}
}
This data should then be converted to:
273
--> 275
--> 274
--> 276
--> 277
278
etc..