按键在多维数组中搜索并返回子数组

时间:2018-02-19 22:39:35

标签: php arrays search multidimensional-array

我有多维数组,我想通过其键提取子数组。 示例数组:

[libra] => Array
    (
        [schema_id] => LibraModel
        [libra_guid] => a2d02184-5a83-0f1b-673d-7f215fe6ba02
        [is_test_client] => 
        [is_web_bot] => 
        [tag_collection] => Array
            (
                [schema_id] => TestGroupAssignmentModel
                [tags_by_test] => Array
                    (
                        [checked] => Array
                            (
                                [first] => Tester
                                [second] => de11e041-1083-44bb-96dc-134fa099f737
                                [control] => false
                            )

                        [optionSelected] => Array
                            (
                                [schema_id] => TestGroupAssignmentModel
                                [test_group_guid] => 6a28c568-a416-4d3a-a993-4eb7f6ce19d3
                                [control] => 
                                [test_name_hash] => ecdd6bf92e27aa10ca5e3acbe385fb6b
                                [fully_qualified_hash] => 9e97e3244516f219887294435975df22
                                [do_not_track] => 
                            )
                    )
            )
    )

从这个数组我想只得到optionSelected,并保持它的结构。

到目前为止我做的最佳功能是:

$multi_array是上面显示的数组,

$array_key是字符串' optionSelected'

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($multi_array));
foreach($iterator as $key => $value) {
    if($array_key == $key){
        echo $key;
    }
}

1 个答案:

答案 0 :(得分:0)

这应该完成工作:

<?php
$array = [
'test' => 'value',
'level_one' => [
    'level_two' => [
        'level_three' => [
            'replace_this_array' => [
                'special_key' => 'replacement_value',
                'key_one' => 'testing',
                'key_two' => 'value',
                'four' => 'another value'
            ]
        ],
        'ordinary_key' => 'value'
    ]
]
];

$recursiveIterator = new \RecursiveIteratorIterator(
    new \RecursiveArrayIterator($array),
    \RecursiveIteratorIterator::SELF_FIRST
);
$extractKey = "level_three";
$result = [];

foreach ($recursiveIterator as $key => $value) {
    if ($key === $extractKey) {
        $result = $value;
    }
}

var_dump($result);

感谢\RecursiveIteratorIterator::SELF_FIRST$value将始终包含整个子数组。