递归遍历对象

bon*_*nez 4 php recursion

我在编写递归函数以遍历此层次结构时遇到麻烦

    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....>
Run Code Online (Sandbox Code Playgroud)

如您所见,此嵌套集可以永远继续下去。

我要退货是这样的

$categories("Root" => array("Root MySite.com" => array("Widgets" => array("Blue Widgets",...))))
Run Code Online (Sandbox Code Playgroud)

[编辑]:为我的递归函数粘贴我的起点,该函数将简单地“拉平”一个对象或对象。我认为我可以对其进行修改,以获取所需的数据结构,但还无法使其完全正确。

    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;
}
Run Code Online (Sandbox Code Playgroud)

问题是我不能完全弄清楚要递归构建的结构,还是有一种更优雅的php方式来做到这一点?

Chv*_*off 5

尝试这个

function run($o) {
    $return = array();
    foreach ($o->children as $child) {
        $return[$child->name] = run($child);
    }

    return empty($return) ? null : $return;
}
Run Code Online (Sandbox Code Playgroud)