首页 > 解决方案 > 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() 函数,除了作者匹配的是键而不是值。这对我来说是个问题,因为我的密钥不是唯一的,但我的价值是。

标签: phparrays

解决方案


递归函数绝对是与未知数量的父母一起走的路。

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);

推荐阅读