Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 740
Run Avatar asked Dec 05 '25 10:12

Run


1 Answers

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

$array = get_letter('a');
like image 105
472084 Avatar answered Dec 07 '25 22:12

472084



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!