You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从给定多维数组生成符合要求格式的面包屑路径?

实现方案

实现思路

  • 采用递归方式遍历多维数组
  • 遍历过程中持续记录从根节点到当前层级的键名路径
  • 当遇到非数组类型的叶子节点时,将当前路径拼接为面包屑格式输出

PHP代码实现

首先定义示例数组:

$arr = [
    'note' => [
        'to' => [
            'user' => [
                'name' => 'First User'
            ],
            'abc' => 123,
            'lmn' => 4582
        ],
        'from' => 'Jani',
        'heading' => 'Reminder',
        'body' => [
            'abc' => 123
        ]
    ]
];

编写递归生成面包屑的函数:

function generateBreadcrumb($array, $prefix = '') {
    foreach ($array as $key => $value) {
        // 拼接当前层级路径
        $currentPath = $prefix ? $prefix . ' > ' . $key : $key;
        if (is_array($value)) {
            // 当前值为子数组,继续递归遍历
            generateBreadcrumb($value, $currentPath);
        } else {
            // 当前值为叶子节点,输出面包屑路径
            echo $currentPath . PHP_EOL;
        }
    }
}

// 调用函数执行
generateBreadcrumb($arr);

如果需要把所有路径存入数组返回,可以使用以下版本的函数:

function getBreadcrumbList($array, $prefix = '', &$result = []) {
    foreach ($array as $key => $value) {
        $currentPath = $prefix ? $prefix . ' > ' . $key : $key;
        if (is_array($value)) {
            getBreadcrumbList($value, $currentPath, $result);
        } else {
            $result[] = $currentPath;
        }
    }
    return $result;
}

// 调用获取路径数组
$breadcrumbList = getBreadcrumbList($arr);

输出结果

note > to > user > name
note > to > abc
note > to > lmn
note > from
note > heading
note > body > abc

内容的提问来源于stack exchange,提问作者Dev Frnds

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 21:06:03