I want to write a function that takes an array of pages / categories (from the result of a flat database) and generates an array of nested page / category elements based on the identifiers of the parent elements. I would like to do this recursively so that any level of nesting can be done.
For example: I retrieve all the pages in one query, and it looks like the database table
+-------+---------------+---------------------------+ | id | parent_id | title | +-------+---------------+---------------------------+ | 1 | 0 | Parent Page | | 2 | 1 | Sub Page | | 3 | 2 | Sub Sub Page | | 4 | 0 | Another Parent Page | +-------+---------------+---------------------------+
And this is the array that I would like to process in my view files:
Array ( [0] => Array ( [id] => 1 [parent_id] => 0 [title] => Parent Page [children] => Array ( [0] => Array ( [id] => 2 [parent_id] => 1 [title] => Sub Page [children] => Array ( [0] => Array ( [id] => 3 [parent_id] => 1 [title] => Sub Sub Page ) ) ) ) ) [1] => Array ( [id] => 4 [parent_id] => 0 [title] => Another Parent Page ) )
I looked and tried almost all the solutions that I came across (there are a lot of them here in Stack Overflow, but it was not lucky to get something in common that would work for both pages and categories.
Here is the closest I got, but it does not work, because I assign children to the parent level of the first level.
function page_walk($array, $parent_id = FALSE) { $organized_pages = array(); $children = array(); foreach($array as $index => $page) { if ( $page['parent_id'] == 0) // No, just spit it out and you're done { $organized_pages[$index] = $page; } else // If it does, { $organized_pages[$parent_id]['children'][$page['id']] = $this->page_walk($page, $parent_id); } } return $organized_pages; } function page_list($array) { $fakepages = array(); $fakepages[0] = array('id' => 1, 'parent_id' => 0, 'title' => 'Parent Page'); $fakepages[1] = array('id' => 2, 'parent_id' => 1, 'title' => 'Sub Page'); $fakepages[2] = array('id' => 3, 'parent_id' => 2, 'title' => 'Sub Sub Page'); $fakepages[3] = array('id' => 4, 'parent_id' => 3, 'title' => 'Another Parent Page'); $pages = $this->page_walk($fakepages, 0); print_r($pages); }
function arrays php recursion
David Hemphill Dec 21 '11 at 9:09 2011-12-21 09:09
source share