Rebuild the array by parent / child identifiers. Recursion?

I have an array of locations. Each of these places may have child locations. Each of the affiliated locations may also have children, etc .:

$locations = array( array("id" => 1, "parent_id" => 0, "name" => "England"), array("id" => 2, "parent_id" => 0, "name" => "Scotland"), array("id" => 3, "parent_id" => 0, "name" => "Ireland"), array("id" => 4, "parent_id" => 0, "name" => "Wales"), array("id" => 5, "parent_id" => 1, "name" => "East England"), array("id" => 6, "parent_id" => 1, "name" => "London"), array("id" => 7, "parent_id" => 6, "name" => "West London"), array("id" => 8, "parent_id" => 6, "name" => "East London"), array("id" => 9, "parent_id" => 1, "name" => "East Midlands"), array("id" => 10, "parent_id" => 9, "name" => "Derbyshire") ); 

I want to restructure this array so that children are parent arrays. Something like this (untested):

 $locations = array("id" => 1, "parent_id" => 0, "name" => "England", "children" => array( array("id" => 5, "parent_id" => 1, "name" => "East England"), array("id" => 6, "parent_id" => 1, "name" => "London", "children" => array( array("id" => 7, "parent_id" => 6, "name" => "West London"), array("id" => 8, "parent_id" => 6, "name" => "East London"))))); 

That way, I can print them using indentation like this:

 LOCATIONS England - East England - London -- West London -- East London - East Midlands -- Derbyshire Scotland Ireland Wales 

I tried several ways, for example, grouping them by parent ID, but I just can’t work out the logic for this, and there may be a better way to do this (recursion, maybe?).

Thank you very much.

+4
source share
2 answers

Hi, maybe this will help you, I just wrote it to quickly convert the mysql result containing parent_id into a useful data hierarchy. Your input array should also work. These are just a couple of lines with two main loops. No recursion required. Some comments included:

 <?php $max = count($inputArray); $tree = array(); $flat = array(); // Create a flat hierarchy array of all entries by their id for ($i = 0; $i < $max; $i++) { $n = $inputArray[$i]; $id = $n['page_id']; $flat[$id] = $n; } // Then check all those entries by reference foreach ($flat as $key => &$child) { // Add a children array if not already existing if (!isset($child['children'])) $child['children'] = array(); $id = $child['page_id']; $pid = $child['parent_id']; // If childs parent id is larger then zero if ($pid > 0) { // Append it by reference, which means it will reference // the same object across different carriers $flat[$pid]['children'][] = &$child; } else { // Otherwise it is zero level, which initiates the tree $tree[$id] = &$child; } } $tree = array_values($tree); // Indices fixed, there we go, use $tree further ?> 

So, pay attention to the '& links. "They do all the work that allows you to build a tree from a flat array, pointing to the same objects.

+2
source

All Articles