Access Multidimensional Array element with out knowing parent elements

爷,独闯天下 提交于 2019-12-30 14:39:48

问题


I have function that returns the following multidimensional array. I don't have control of how the array is formed. Im trying to access the 'Result' elements. This issue is, the name of the parent elements constantly changing. The location of the 'Result' element is always the same (as the is the name "Result"). Is it possible to access that element without know the name of the parent elements?

    Array
(
    [sHeader] => Array
        (
            [aAction] => ActionHere
        )

[sBody] => Array
    (
        [CreatePropertyResponse] => Array
            (
                [CreatePropertyResult] => Array
                    (
                        [Message] => Successfully completed the operation
                        [Result] => 0
                        [TransactionDate] => 2013-05-19T21:54:35.765625Z
                        [bPropertyId] => 103
                    )

            )

    )

)


回答1:


An easy option to search the array keys/values recursively is to use a recursive iterator; these are built-in classes, part of the Standard PHP Library.

$result   = false;
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iterator as $key => $value) {
    if ($key === 'Result') {
        $result = $value;
        break;
    }
}

var_dump($result);

The bonus here is that you could, if you wanted to, check the depth of the Result item ($iterator->getDepth()) in the array structure and/or check one or more ancestor keys ($iterator->getSubIterator(…)->key()).




回答2:


If the parent elements have only one child, you can solve it by getting the only element given back by array_keys(), and going two levels deep.

Anyway, if your array changes that much, and you systematically have to access a nested property, you have a design issue for sure.




回答3:


Edit: array_column won't actually work in this case. You could search through each level, recursively, until you find the given key. Something like:

function find_key_value($array, $search_key) {
    if (isset($array[$search_key])) return $array[$search_key];
    $found = false;
    foreach ($array as $key=>$value) {
         if (is_array($value)) $found = find_key_value($value, $search_key);
         if ($found) return $found; 
    }
    return false;
}



回答4:


function findkeyval($arr,$key) {
    if(isset($arr[$key])) {
        return $arr[$key];
    }else {
        foreach($arr as $a) {
            if(is_array($a)) {
                $val=findkeyval($a,$key);
                if($val) {
                   return $val;
                }
            }
        }
    }
}


来源:https://stackoverflow.com/questions/16639932/access-multidimensional-array-element-with-out-knowing-parent-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!