加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 对象的递归遍历

发布时间:2020-12-13 17:22:49 所属栏目:PHP教程 来源:网络整理
导读:我在写一个递归函数来遍历这个层次结构时遇到了麻烦 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
我在写一个递归函数来遍历这个层次结构时遇到了麻烦

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....>

正如你所看到的,这个嵌套集可以永远持续下去.

我想要归还的是这样的

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

[编辑]:粘贴我的递归函数的起点,简单地“展平”一个arry或对象.我想我可以修改这个以获得我正在寻找的数据结构但是却无法完全正确.

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;
}

问题是我不能完全弄清楚我正在寻找递归的结构,或者可能有更优雅的PHP方式来做到这一点?

解决方法

试试这个

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

    return empty($return) ? null : $return;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读