3

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?

hakre
  • 193,403
  • 52
  • 435
  • 836
Run
  • 54,938
  • 169
  • 450
  • 748

5 Answers5

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');
472084
  • 17,666
  • 10
  • 63
  • 81
0

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";
  }
}
Mads Ohm Larsen
  • 3,315
  • 3
  • 20
  • 22
0

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

foreach ($array as $key => $value) {
    if (array_key_exists('b', $array[$key])) {
        return $array[$key]['b'];
    }
}
HBv6
  • 3,487
  • 4
  • 30
  • 43
0

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'];
goat
  • 31,486
  • 7
  • 73
  • 96
0

Nice another variant:

array_merge(... $array)['b']
dikirill
  • 1,873
  • 1
  • 19
  • 21