【问题标题】:How do i get data based on the id in the array php如何根据数组php中的id获取数据
【发布时间】:2019-11-21 10:02:36
【问题描述】:

如何根据数组中的id获取数据

array:60[
 3 => array:3[
  "id" => 4
  "name" => james
  "sex" => male
  ],
3 => array:3[
  "id" => 5
  "name" => mulan
  "sex" => female
  ]

]

我用的是laravel,我用的是下面这样的代码,但是过滤的是不基于id的索引数组

 $response = Curl::to('127.0.0.2:8000/user/data')->get();
        $data = json_decode($response, true);    
        $outputData = $data["data"];
        dd($outputData[$request->id]);

【问题讨论】:

    标签: php arrays laravel search filter


    【解决方案1】:

    您可以将该数组放入一个集合中,并使用where 方法返回基于id 的项目:

    $collection = collect($thatArray);
    
    $item = $collection->where('id', 5);
    

    您也可以通过 'id' 来键入集合,然后您可以使用 get:

    $collection = collect($thatArray)->keyBy('id');
    
    $item = $collection->get(5);
    

    Laravel 6.x Docs - Collections - Available Methods - where

    Laravel 6.x Docs - Collections - Available Methods - keyBy

    Laravel 6.x Docs - Collections - Available Methods - get

    【讨论】:

      猜你喜欢
      • 2018-07-31
      • 2013-01-21
      • 2016-10-02
      • 2019-11-22
      • 2019-12-03
      • 2020-09-01
      • 2019-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多