递归循环数组的每个路径 [英] Recursively cycle every path of an array

查看:90
本文介绍了递归循环数组的每个路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下(json)对象:

I have the following(json) object:

$obj = json_decode('{
    "Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        },
        "Green": {
            "Round": [
                "Harold"
            ],
            "Circle": [
                "Todd",
                "Mike"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}', true);

我试图弄清楚如何递归地遍历它,以便可以看到数组中所有不同的路径.

I'm trying to figure out how to recursively travel through it so I can see all the different paths that is in the array.

它可以是4个单独的回显或4行字符串. >可以替换为任何东西或根本不替换.如果每行分别回显或推入可能会提供最大灵活性的数组.

It could be 4 separate echo's or a 4 line string. The > could be replaced with anything or nothing at all. If each line was echo'd separately or pushed to an array that would probably give the most flexibility.

Group1 - Blue - Round - (Harold, Arthur, Tom)
Group1 - Green - Round - (Harold)
Group1 - Green - Circle - (Todd, Mike)
Group2 - Blue - Round - (Peter)

我无法将其包裹住,因此将不胜感激.

I can't wrap my head around it so any help would be appreciated.

我想我可以以某种方式在每个人之间循环:

I'm thinking I can somehow cycle through each like:

foreach($obj as $index => $value)
{
   // and then somehow do this until you reach an array?
}

推荐答案

仅在给定样本上进行了测试.但是,如果增加阵列级别,这应该可以工作.我主要使用RecursiveIteratorIterator类函数

Tested only on the given sample. But this should work if array levels are increased. I mainly use RecursiveIteratorIterator class functions

// Initialize RecursiveIteratorIterator
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($obj), RecursiveIteratorIterator::SELF_FIRST);
$paths = array(); // Paths storage
foreach ($iterator as $k => $v) { // Loop thru each iterator

    if (!$iterator->hasChildren()) { // Check if iterator hasChildren is false
        $innermost = $iterator->getSubIterator($iterator->getDepth()); // Get innermost child which is the array
        for ($p = array(), $i = 0, $z = $iterator->getDepth(); $i <= $z; $i++) { // Loop and push each path to the innermost array
            $p[] = $iterator->getSubIterator($i)->key();
        }
        array_pop($p); // Remove key
        $innermost = (array)$innermost; // Cast innermost to array
        $p[] = '(' . implode(', ', $innermost) . ')'; // push formatted innermost array to path
        $path = implode(' - ', $p); // implode the path
        $paths[] = $path; // store to list of paths array
    }

}

$paths = array_unique($paths); // remove exactly same paths

foreach ($paths as $value) {  // Loop and echo each path
    echo $value.'<br>';
}

输出:- https://eval.in/915070

这篇关于递归循环数组的每个路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆