我如何基于数组php中的ID获取数据

问题描述 投票:0回答:1

如何根据数组中的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个回答
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

where

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

© www.soinside.com 2019 - 2024. All rights reserved.