php - PHP多维数组:当元素值具有唯一ID时提取父数组
问题描述
我有一个级别数未知的多维数组。如果子数组元素包含唯一值,那么如何提取父数组以在 PHP 中使用?
我的数组看起来与此类似,除了我不知道键/值有多少祖父母(或者这会容易得多)。
Array (
[0] => Array
(
[blockName] => core/group,
[attrs] => Array ( ),
[innerBlocks] => Array
(
// I want to extract this array if its [attrs] element contains [wrapper-id] => myUniqueID
// The number of parents and grandparents is unknown. This is only an example.
// Notice that other arrays contain attrs elements, but the value of this one is unique.
[0] => Array
(
[blockName] => lazyblock/zurb-tabs-wrapper,
[attrs] => Array
(
[wrapper-id] => myUniqueID, // This unique ID value is known.
[blockId] => T,
[blockUniqueClass] => lazyblock-zurb-tabs-wrapper-T
),
[innerBlocks] => Array ()
),
// Later, I'll also want to extract this array based on its unique wrapper-id class.
[1] => Array
(
[blockName] => lazyblock/zurb-tabs-wrapper,
[attrs] => Array
(
[wrapper-id] => anotherUniqueID, // This unique ID value is known.
[blockId] => T,
[blockUniqueClass] => lazyblock-zurb-tabs-wrapper-T
),
[innerBlocks] => Array ()
)
)
)
)
找到到父级的路径也可能有效,这样我就可以走到我需要的值而无需提取。该解决方案类似于 Drummin 中的 getkeypath() 函数,除了作者匹配的是键而不是值。这对我来说是个问题,因为我的密钥不是唯一的,但我的价值是。
解决方案
递归函数绝对是与未知数量的父母一起走的路。
function getBlock(array $blocks, string $id): ?array
{
foreach ($blocks as $block)
{
// if the block has a wrapper-id attr and it matches the requested id, return it
if (!empty($block['attrs']['wrapper-id']) && $block['attrs']['wrapper-id'] === $id)
{
return $block;
}
// check if we have inner blocks to iterate
if (!empty($block['innerBlocks']))
{
$innerBlock = getBlock($block['innerBlocks'], $id);
if (!empty($innerBlock)) {
return $innerBlock;
}
}
}
// fallback empty response
return null;
}
然后,您将getBlock
使用父数组调用该方法。
$block = getBlock($blocks);
推荐阅读
- azure-devops - Azure DevOps 上的深色主题何时启用?
- node.js - 如何使用 Node.js 从 Azure 表存储中获取表列表?
- .htaccess - .htaccess,如何将语言组合并添加到路径
- c# - Rhinoscript MoveObject Python 到 C#
- node.js - 编译另一个没有所有引用的打字稿输出目录
- c# - NLog 出现“无法加载 System.XML 版本 2.0.5.0”异常
- c# - 遍历对象列表,检查它们的属性是否已定义
- xml - Ofbiz:一个带有两个提交按钮的表单,带有两个不同的目标
- javascript - 如何在javascript中修复无序的“获取”
- regex - 用于排除多个字符串的正则表达式