微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PHP-递归函数来循环未知深度的数组在两个级别之后不传递/保持父键

如何解决PHP-递归函数来循环未知深度的数组在两个级别之后不传递/保持父键

我想要一些有关如何处理此用例的建议:

我具有以下未知深度的多维测试数组:

Greeting_2

然后我尝试使用此递归函数遍历数组以执行一些逻辑(从示例中排除):

$entries =
[
    [
        'id' => 'Foo','parent' => 'root','logic_rules' => []
    ],[
        'id' => 'Bar','logic_rules' => [],'children' => [
            [
                'id' => 'Foobar','parent' => 'Bar','children' => [
                    [
                        'id' => 'Foobar2','parent' => 'Foobar','children' => [
                            [
                                'id' => 'Foobar3','parent' => 'Foobar2','logic_rules' => []
                            ]
                        ]
                    ]
                ]
            ]
        ]
    ]
];

function traverse(array $entries,array &$result = []) { foreach ($entries as $k => $value) { // If `logic_rules` exists proceed executing the logic // and store the result in the same `parent -> id` position if (array_key_exists('logic_rules',$value)) { $result[$value['parent']][$value['id']]['logic_rules'] = time(); // some logic } // Re-loop if is parent if (array_key_exists('children',$value)) { traverse($value['children'],$result); } } return $result; } 输出是:

traverse($entries)

但是我希望这样:

Array
(
    [root] => Array
        (
            [Foo] => Array
                (
                    [logic_rules] => 1603091236
                )

            [Bar] => Array
                (
                    [logic_rules] => 1603091236
                )

        )

    [Bar] => Array
        (
            [Foobar] => Array
                (
                    [logic_rules] => 1603091236
                )

        )

    [Foobar] => Array
        (
            [Foobar2] => Array
                (
                    [logic_rules] => 1603091236
                )

        )

    [Foobar2] => Array
        (
            [Foobar3] => Array
                (
                    [logic_rules] => 1603091236
                )

        )

)

似乎在跳过其祖先。有什么建议吗?

解决方法

解决方案是refer to the results parent,因此以下深度将推向该深度。

看这行:

traverse($value['children'],$result[$value['parent']]);

此代码将为您工作:

function traverse (array $entries,array &$result = []) {
  foreach ($entries as $value) {
    
      // add your logical stuff here
      $result[$value['parent']][$value['id']] = array(
        'logical_rules' => time()
      );

    if (array_key_exists('children',$value)) {
      traverse($value['children'],$result[$value['parent']]);
    }
  }
  return $result;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。