Find a key exists in the sub keys of an array?

梦想与她 提交于 2020-01-03 19:58:10

问题


How can I check if a key exists in the sub keys of an array? And if that key of the item is found then return that item?

For instance, I have this array,

Array
(
    [0] => Array
        (
            [a] => Array
                (
                    [quantity_request] => 1
                    [time_created] => 1339688613
                    [variant] => Array
                        (
                        )

                )

        )

    [1] => Array
        (
            [b] => Array
                (
                    [quantity_request] => 1
                    [time_created] => 1339688631
                    [variant] => Array
                        (
                        )

                )

        )

    [2] => Array
        (
            [c] => Array
                (
                    [quantity_request] => 1
                    [time_created] => 1339688959
                    [variant] => Array
                        (
                        )

                )

        )

)

I want to find key 'b' and return everything under it, like this is what I am after,

[b] => Array
                (
                    [quantity_request] => 1
                    [time_created] => 1339688631
                    [variant] => Array
                        (
                        )

                )

I try with this, but nothing returns,

if (array_key_exists('b', $this->content)) {
                echo "The 'b' element is in the array";

}

Any ideas?


回答1:


function get_letter($letter){
    foreach($this->content as $v){
        if(array_key_exists($letter, $v) {
            return $v[$letter];
        }
    }
    return false;
}

$array = get_letter('a');



回答2:


Couldn't you just loop over the outer array, checking each array inside for the key?

foreach($this->content as $arr) {
  if(array_key_exists('b', $arr) {
    echo "Found it";
  }
}



回答3:


foreach() the root Array, then array_key_exists().

foreach ($array as $key => $value) {
    if (array_key_exists('b', $array[$key])) {
        return $array[$key]['b'];
    }
}



回答4:


The code here looks ok, but I wonder where the array is coming from or where it is defined? One suggestion that may narrow it down is to use is_array on $this->content to make sure it is a proper array.




回答5:


I wouldn't actually use this because it's not clear code, but, it's a cool one liner for php 5.4

$val = call_user_func_array('array_merge', $array)['b'];


来源:https://stackoverflow.com/questions/11036969/find-a-key-exists-in-the-sub-keys-of-an-array

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