phpmultidimensional-arrayarray-key-exists

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


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?


Solution

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