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?
source share