Recursive object traversal

I am having trouble writing a recursive function to move this hierarchical structure

object(stdClass)#290 (6) { ["category_id"]=> int(1) ["parent_id"]=> int(0) ["name"]=> string(4) "Root" ["position"]=> int(0) ["level"]=> int(0) ["children"]=> array(2) { [0]=> object(stdClass)#571 (7) { ["category_id"]=> int(2) ["parent_id"]=> int(1) ["name"]=> string(18) "Root MySite.com" ["is_active"]=> int(0) ["position"]=> int(0) ["level"]=> int(1) ["children"]=> array(11) { [0]=> object(stdClass)#570 (7) { ["category_id"]=> int(15) ["parent_id"]=> int(2) ["name"]=> string(9) "Widgets" ["is_active"]=> int(1) ["position"]=> int(68) ["level"]=> int(2) ["children"]=> array(19) { [0]=> object(stdClass)#566 (7) { ["category_id"]=> int(24) ["parent_id"]=> int(15) ["name"]=> string(16) "Blue widgets" ["is_active"]=> int(1) ["position"]=> int(68) ["level"]=> int(3) ["children"]=> array(0) { } } <snip....> 

As you can see, this nested set can go on forever ..

What I want to return is something like this

 $categories("Root" => array("Root MySite.com" => array("Widgets" => array("Blue Widgets",...)))) 

[EDIT]: Inserting my starting point for my recursive function, which simply β€œsmoothes” the arry or object. I would think that I could change this to get the data structure that I am looking for, but could not get it completely correctly.

  function array_flatten($array, $return) { // `foreach` can also iterate through object properties like this foreach($array as $key => $value) { if(is_object($value)) { // cast objects as an array $value = (array) $value; } if(is_array($value)) { $return = array_flatten($value,$return); } else { if($value) { $return[] = $value; } } } return $return; } 

The question is, I cannot figure out how to build the structure that I am looking for recursively, or maybe there is a more elegant php way for this?

+4
source share
2 answers

try it

 function run($o) { $return = array(); foreach ($o->children as $child) { $return[$child->name] = run($child); } return empty($return) ? null : $return; } 
+4
source

I don’t have time to write a working answer, but there is some kind of pseudo code here (half PHP, half JS)

This would create a smoothed version of the tree by removing the child property of each item in your list.

 $flattened = array(); function addElement(&$flattened, $list) { for ($element in $list) { $children = $element->children; delete $element->children; $flattened[] = $element; if ($children) { addElements($flattened, $children) } } } addElements($flattened, $treeHierarchy); 
+1
source

All Articles