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

递归搜索不确定深度的多维数组,获取目标值的完整索引路径

在PHP中获取嵌套数组中目标值的完整索引路径

实现思路

  • 递归或迭代遍历嵌套数组,全程维护当前遍历的路径
  • 每进入一个层级就将当前的键名/索引加入路径
  • 找到目标值时,将路径拼接为符合PHP语法的字符串格式
  • 支持任意层级的数组,包括100层以上

递归实现代码

function findValuePath($array, $target, &$currentPath = []) {
    foreach ($array as $key => $value) {
        // 记录当前层级的键
        $currentPath[] = is_string($key) ? "'$key'" : $key;
        
        if ($value === $target) {
            // 找到目标,返回拼接后的路径
            return '$array[' . implode('][', $currentPath) . ']';
        } elseif (is_array($value)) {
            // 递归遍历子数组
            $result = findValuePath($value, $target, $currentPath);
            if ($result !== null) {
                return $result;
            }
        }
        
        // 回溯,移除当前键,继续遍历同级元素
        array_pop($currentPath);
    }
    return null;
}

// 测试用示例数组
$array = [
    [
        'id' => 67941,
        'parent_id' => 0,
        'name' => 'Requirement',
        'children' => [
            [
                'id' => 67942,
                'parent_id' => 67941,
                'name' => 'Sub Requirement',
                'children' => [
                    [
                        'id' => 67943,
                        'parent_id' => 67942,
                        'name' => 'Sub Sub Requirement',
                    ],
                ],
            ],
        ],
    ],
];

// 查找目标值67943的路径
$path = findValuePath($array, 67943);
echo $path; // 输出:$array[0]['children'][0]['children'][0]['id']

代码说明

  • 用引用传递的$currentPath维护路径,减少内存开销
  • 关联数组的键会自动加上单引号,保证路径格式合法
  • 找到目标后立即返回,无需遍历剩余元素,提升效率
  • 遍历完当前层级后自动回溯路径,确保后续遍历的正确性

迭代实现(避免递归深度限制)

如果数组层级超过PHP默认递归深度(通常100-200层),可以用栈实现迭代遍历,彻底规避递归限制:

function findValuePathIterative($array, $target) {
    $stack = [[$array, []]];
    
    while (!empty($stack)) {
        list($currentArray, $currentPath) = array_pop($stack);
        
        foreach ($currentArray as $key => $value) {
            $newPath = $currentPath;
            $newPath[] = is_string($key) ? "'$key'" : $key;
            
            if ($value === $target) {
                return '$array[' . implode('][', $newPath) . ']';
            } elseif (is_array($value)) {
                // 将子数组和新路径压入栈
                array_push($stack, [$value, $newPath]);
            }
        }
    }
    return null;
}

// 使用方式
$path = findValuePathIterative($array, 67943);
echo $path;

额外说明

  • 如果数组中有多个相同的目标值,两种实现都会返回第一个找到的路径
  • 若需要收集所有匹配的路径,可修改代码将路径存入数组而非直接返回

内容的提问来源于stack exchange,提问作者Asad Seeker

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 07:32:53