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

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

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用