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

PHP未知层级多维数组根据子元素唯一ID提取对应父数组的实现方法

PHP未知嵌套层级多维数组匹配指定值提取父数组实现方案

实现思路

  • 采用递归深度遍历整个多维数组,不需要提前知道嵌套层级
  • 遍历每个元素时判断是否为数组,若为数组则优先检查是否包含目标键值对
  • 匹配成功后可按需返回匹配到的数组本身,或者返回该数组的访问路径

直接返回匹配数组的实现代码

function findParentArrayByValue(array $array, string $targetKey, mixed $targetValue) {
    foreach ($array as $item) {
        if (!is_array($item)) {
            continue;
        }
        // 适配你给出的结构,检查attrs下的目标键值对
        if (isset($item['attrs']) && is_array($item['attrs']) 
            && isset($item['attrs'][$targetKey]) 
            && $item['attrs'][$targetKey] === $targetValue) {
            return $item;
        }
        // 递归遍历innerBlocks子数组
        if (isset($item['innerBlocks']) && is_array($item['innerBlocks'])) {
            $result = findParentArrayByValue($item['innerBlocks'], $targetKey, $targetValue);
            if ($result !== null) {
                return $result;
            }
        }
        // 如需完全通用不限制子数组键名,可将上面的innerBlocks判断替换为遍历所有子元素:
        // foreach ($item as $subItem) {
        //     if (is_array($subItem)) {
        //         $result = findParentArrayByValue([$subItem], $targetKey, $targetValue);
        //         if ($result !== null) return $result;
        //     }
        // }
    }
    return null;
}

调用示例

// 匹配wrapper-id为myUniqueID的父数组
$targetArray = findParentArrayByValue($yourMultiArray, 'wrapper-id', 'myUniqueID');
// 匹配成功返回对应数组,匹配失败返回null

返回访问路径的实现代码

如果需要获取数组的访问路径方便后续操作原数组,可以使用以下版本:

function findArrayPathByValue(array $array, string $targetKey, mixed $targetValue, array $path = []) {
    foreach ($array as $key => $item) {
        $currentPath = array_merge($path, [$key]);
        if (!is_array($item)) {
            continue;
        }
        // 匹配attrs下的目标键值对
        if (isset($item['attrs']) && is_array($item['attrs']) 
            && isset($item['attrs'][$targetKey]) 
            && $item['attrs'][$targetKey] === $targetValue) {
            return $currentPath;
        }
        // 递归遍历innerBlocks
        if (isset($item['innerBlocks']) && is_array($item['innerBlocks'])) {
            $result = findArrayPathByValue($item['innerBlocks'], $targetKey, $targetValue, array_merge($currentPath, ['innerBlocks']));
            if ($result !== null) {
                return $result;
            }
        }
    }
    return null;
}

路径使用示例

$path = findArrayPathByValue($yourMultiArray, 'wrapper-id', 'myUniqueID');
// 返回的路径格式示例:[0, 'innerBlocks', 0]
// 可通过路径直接访问原数组对应元素
$target = $yourMultiArray[$path[0]][$path[1]][$path[2]];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 05:39:01