列出多维数组的所有路径

时间:2015-01-06 09:21:57

标签: php

所以我得到了这个:

$tree = [
    array(
        'name' => 'One1',
    ),
    array(
        'name' => 'One2',
    ),
    array(
        'name' => 'One3',
    ),
    array(
        'name' => 'One4',
        'children' => [
            array(
                'name' => 'Two1',
            ),
            array(
                'name' => 'Two2',
                'children' => [
                    array(
                        'name' => 'Three1',
                    ),
                ],
            ),
            array(
                'name' => 'Two3',
            ),
        ]
    ),
    array(
        'name' => 'One5',
    ),
];

我正在寻找一种方法来获得此输出(递归):

  • One1
  • One2
  • One3
  • One4> Two1
  • One4> Two2> Three1
  • One4> Two3
  • One5

据我所知,我有这个功能

function getValuesPaths(array $tree, $glue = ' > ') {
    $branches = array();
    foreach ($tree as &$item) {
        $piece = $item['name'];
        if (array_key_exists('children', $item)) {
            if (count($item['children'])>1) {
                $leafs = self::getValuesPaths($item['children']);
                foreach ($leafs as $item) {
                    $branches[] = $piece . $glue . $item;
                }
            }   
        } else {
            $branches[] = $piece;
        }
    }
    return $branches;
}

这输出以下路径:

  • One1
  • One2
  • One3
  • One4> Two1
  • One4> TWO3
  • One5

我们不应该找到One4 > Two2 > Three1

1 个答案:

答案 0 :(得分:0)

可以帮助你......

function getKeyPaths(array $tree, $glue = '.')
{
    $paths = array();
    foreach ($tree as $key => &$mixed) {
        if (is_array($mixed)) {
            $results = getKeyPaths($mixed, $glue);
            foreach ($results as $k => &$v) {
                $paths[$key . $glue . $k] = $v;
            }
            unset($results);
        } else {
            $paths[$key] = $mixed;
        }
    }

    return $paths;
}