JustLearn JustLearn - 4 months ago 15
PHP Question

Retrieve value of child key in multidiensional array without knowing parent key

Given this multidimensional array, I'm trying to retrieve the value of one of the child keys:

$movieCast = Array(
'1280741692' => Array(
...
, 'userid' => 62
, 'country_id' => '00002'
...
)
, '1280744592' => Array(
...
, 'userid' => 62
, 'country_id' => '00002'
...
)
)


How can I retrieve the value of
country_id
?

The top-level array key could be anything and the value of
country_id
will always be the same for a specific user. In this example, user #62's
country_id
will always be
00002
.

Answer

You have to iterate through the outer array:

foreach ($outer as $inner) {
    //do something with $inner["country_id"]
}

Another option is to build an array with the contry_ids (example uses PHP >=5.3 functionality, but that can be worked around easily in earlier versions):

array_map(function ($inner) { return $inner["country_id"]; }, $outer);

EDIT If the ids are all the same, even easier. Do:

$inner = reset($outer); //gives first element (and resets array pointer)
$id = $inner["country_id"];
Comments