使用全键路径打印多维数组的最终值

时间:2018-12-16 22:57:23

标签: php arrays

我有多维数组,例如:

$input = [
    'a' => [
        'b' => 'c', 
        'd' => 'e',
        'f' => [
            'g' => 'h'
        ],
    ],
    'i' => 'j',
    'k' => [
        'l' => 'm'
    ],
];

我需要使用其完整键路径打印所有非数组值。像这样:

a > b > c
a > d > e
a > f > g > h
i > j
k > l > m

我该怎么做?

1 个答案:

答案 0 :(得分:2)

您需要使用递归函数遍历数组的级别。这应该给您您想要的结果:

function list_paths($input) {
    $paths = array();
    foreach ($input as $k => $v) {
        if (is_array($v)) {
            foreach (list_paths($v) as $path) {
                $paths[] = $k . " > " . $path;
            }
        }
        else {
            $paths[] = $k . " > " . $v;
        }
    }
    return $paths;
}
print_r(list_paths($input));

输出:

Array ( 
    [0] => a > b > c
    [1] => a > d > e
    [2] => a > f > g > h
    [3] => i > j
    [4] => k > l > m 
)

Demo on 3v4l.org