使用全键路径打印多维数组的最终值 [英] Print multidimensional array's end-values with full keys path

查看:57
本文介绍了使用全键路径打印多维数组的最终值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多维数组,例如:

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

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

I need to print all non-array values with the full key path to it. Like this:

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

我该怎么做?

推荐答案

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

You need to use a recursive function to traverse the levels of your array. This should give you your desired results:

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 
)

在3v4l.org上进行演示

这篇关于使用全键路径打印多维数组的最终值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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