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
相关产品推荐
相关产品推荐

