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

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?

图片转代码服务由CSDN问答提供 功能建议

我有以下多维数组:

  Array \  n(
 [0] =>数组
(
 [名称] => Botline 
 [描述] => Kwese 
 [parent_team_id] => 
 [company_id] => 10554 \  n [id] => 13482 
 [external_id] => 13482 
 [extras] => 
)
 
 [1] =>数组
(
 [名称] =>  Books Boutique 
 [描述] => Kwese 
 [parent_team_id] => 
 [company_id] => 10554 
 [id] => 13483 
 [external_id] => 13483 
 [extras  ] => 
)
 
 [2] =>数组
(
 [名称] => Sij Investments 
 [描述] => Kwese 
 [parent_team_id] => 
  [company_id] => 10554 
 [id] => 13484 
 [external_id] => 13484 
 [extras] => 
)
 
 [3] =>数组
(  
 [name] => Steamcard Investments 
 [description] => Kwese instal  lations 
 [parent_team_id] =>  
 [company_id] =>  10554 
 [id] =>  13549 
 [external_id] =>  13549 
 [extras] =>  
)
)
   
 
 

我希望能够在数组中循环搜索一个嵌套数组,该数组的“id”等于“13484” ”。 在我找到'id'后,我希望能够获取该数组中的所有元素并保存它们。

主数组中可能出现的嵌套数组的数量是未定义的,所以 我无法创建一个获得具有匹配值的正确数组的预定方法。 我怎样才能做到这一点?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

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条)

相关推荐 更多相似问题