获取其键具有特定值的数组项

时间:2014-04-27 10:05:12

标签: php arrays

我是PHP的新手,我在我的项目中使用TMDb API。当查询电影或电视节目的工作人员时,api返回如下的数组:

[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] => )

)

我的问题是:如何获取其键[作业]具有“执行制作人”值的项目的所有索引?换句话说,我怎么能回应所有执行制片人的名字?

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以过滤数组

$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';
});

结果

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

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

)

显示名称

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