EDIT
I'm trying to create a little CMS for testing purposes. I've setup a class that creates a navigation with nested elements depending on an array of which the output looks like this:
Array
(
[0] => Array
(
[name] => Home
[link] =>
)
[1] => Array
(
[name] => About us
[link] => about
[children] => Array
(
[0] => Array
(
[name] => Team
[link] => team
)
[1] => Array
(
[name] => History
[link] => history
)
)
)
[2] => Array
(
[name] => Contact
[link] => contact
)
)
It works quite good so far but what I finally need is an array with unlimited nesting possibilities. Something like this:
Array
(
[0] => Array
(
[name] => Home
[link] =>
)
[1] => Array
(
[name] => About us
[link] => about
[children] => Array
(
[0] => Array
(
[name] => Team
[link] => team
)
[1] => Array
(
[name] => History
[link] => history,
[children] => Array
(
[name] => Pictures
[link] => pictures
)
)
)
)
[2] => Array
(
[name] => Contact
[link] => contact
)
)
I'm using the following PHP script to populate the array with data from the db:
/**
* Loops through the children of a page and adds them accordingly to the pages array
*
* @param array $parent
* @param array $children
*/
private function getChildrenPages($parent, $children) {
$subpages = array();
foreach ($children as $child) {
array_push($subpages, array(
'name' => $child['name'],
'link' => $child['link']
));
}
array_push($this->pages, array(
'name' => $parent['name'],
'link' => $parent['link'],
'children' => $subpages
));
}
/**
* @return array Returns an multidimensional associative array with all pages
*/
private function fetchPages() {
// Prevent multiple db fetches
if(!count($this->pages)){
$all_pages = $this->db->get('pages');
for ($i=0; $i < count($all_pages); $i++) {
$parent = $all_pages[$i];
// Get children of current item
$this->db->where('parent_id', $parent['id']);
$children = $this->db->get('pages');
//
if(count($children)) {
$this->getChildrenPages($parent, $children);
}
if (!$parent['parent_id'] && !count($children)) {
// Append current item without children to pages array
array_push($this->pages, array(
'name' => $parent['name'],
'link' => $parent['link']
));
}
}
}
}
This works for 1st and 2nd level items. But how to handle further level items? I guess I'd have to transform my getChildrenPages() function to a recursive function but no clue how to make that in this case. Any suggestions?
parent_idfield per row rather than multiple ids in achildrenfield like you have here. Then you can actuallyJOINon meaningful data instead of having to parse strings.JOINis used for multiple tables as for two rows?