简体   繁体   中英

Get array item whose key has a specific value

I'm fairly new to PHP and I'm using the TMDb API on a project of mine. When queried for the crew of a movie or tv show, the api returns arrays such as this one:

[crew] => Array (
    [0] => Array (
       [credit_id] => 52542287760ee31328001b69
       [department] => Production
       [id] => 5162
       [name] => Mark Johnson
       [job] => Executive Producer
       [profile_path] => /yKGF6cbzyP03Gl1QhVLCu1gWSW6.jpg )

    [1] => Array (
       [credit_id] => 52542288760ee31328001b83
       [department] => Production
       [id] => 29779
       [name] => Michelle MacLaren
       [job] => Executive Producer
       [profile_path] => )

    [2] => Array (
       [credit_id] => 52542287760ee31328001af1
       [department] => Production
       [id] => 66633
       [name] => Vince Gilligan
       [job] => Executive Producer
       [profile_path] => /wSTvJGz7QbJf1HK2Mv1Cev6W9TV.jpg )

    [3] => Array (
       [credit_id] => 52b7008819c29559eb03dd72
       [department] => Sound
       [id] => 1280070
       [name] => Dave Porter
       [job] => Original Music Composer
       [profile_path] => )

)

My question is: How can I get all the indexes of the items whose key [job] has the value "Executive Producer"? In other words, how could I echo the names of all the Executive producers?

Thanks!

You can filter array

$crew = array(
    array(
        'name' => 'Mark',
        'job' => 'Executive Producer'
    ),

    array(
        'name' => 'Johnny',
        'job' => 'Original Music Composer'
    ),

    array(
        'name' => 'Mark',
        'job' => 'Executive Producer'
    ),
);


$executiveProducters = array_filter($crew, function ($array) {
    return $array['job'] == 'Executive Producer';
});

Results

Array
(
    [0] => Array
        (
            [job] => Executive Producer
        )

    [2] => Array
        (
            [job] => Executive Producer
        )

)

Display names

foreach($executiveProducters as $person)
{
    echo $person['name'];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM