duanjumie8753 2017-10-12 17:43
浏览 313
已采纳

PHP循环遍历嵌套数组以查找特定值,然后获取该数组中获取匹配项的所有元素

I have the following multi dimensional array:

Array
(
[0] => Array
    (
        [name] => Botline
        [description] => Kwese
        [parent_team_id] => 
        [company_id] => 10554
        [id] => 13482
        [external_id] => 13482
        [extras] => 
    )

[1] => Array
    (
        [name] => Books Boutique
        [description] => Kwese
        [parent_team_id] => 
        [company_id] => 10554
        [id] => 13483
        [external_id] => 13483
        [extras] => 
    )

[2] => Array
    (
        [name] => Sij Investments
        [description] => Kwese
        [parent_team_id] => 
        [company_id] => 10554
        [id] => 13484
        [external_id] => 13484
        [extras] => 
    )

[3] => Array
    (
        [name] => Steamcard Investments
        [description] => Kwese installations
        [parent_team_id] => 
        [company_id] => 10554
        [id] => 13549
        [external_id] => 13549
        [extras] => 
    )
)

I want to be able to loop through the array searching for a nested array which has a 'id' equal to lest say '13484'. After I find that 'id' I want to be able to get all the elements in that array and save them.

The number of nested arrays which might come in the main array are undefined so I can not create a predetermined way of getting the right array which has the matching value. How can I achieve this?

  • 写回答

3条回答 默认 最新

  • duan0802 2017-10-12 17:53
    关注

    No need to loop, just re-index using the id and then reference that element. This assumes that id is unique:

    $array  = array_column($array, null, 'id');
    $result = $array[13484];
    

    Or if you only need it once:

    $result = array_column($array, null, 'id')[13484];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?