从JSON PHP搜索对象[Laravel]

时间:2018-08-07 12:29:54

标签: php json laravel api

我有像Code in here这样的json数据

此json来自

的结果
$path = public_path() . "/users/project/$endpoint/$id_resource.json";
$file = File::get($path);
return $file

如果我想用URL localhost/show/json?id=1搜索id:1 结果是

[
  {
    "id": 1,
    "Name": {
      "FirstName": "Wilmer",
      "LastName": "Crona",
      "FullName": "Mr. Cameron Prosacco"
    },
    "Address": {
      "Address1": "84154 Vickie Burg Apt. 994",
      "Address2": "Suite 339",
      "ZipCode": "89080-0376"
    },
    "Phone": "316-269-7694 x1364"
  }
]

我该怎么办?

2 个答案:

答案 0 :(得分:1)

尝试return collect($temp)->where('id', $request->get('id'))->first(); $ temp是您的json数据。

答案 1 :(得分:0)

$data='[
  {
    "id": 1,
    "Name": {
      "FirstName": "Wilmer",
      "LastName": "Crona",
      "FullName": "Mr. Cameron Prosacco"
    },
    "Address": {
      "Address1": "84154 Vickie Burg Apt. 994",
      "Address2": "Suite 339",
      "ZipCode": "89080-0376"
    },
    "Phone": "316-269-7694 x1364"
  }
]';


$data=json_decode($data,true);



foreach($data as $row){
    if($row['id']==$_GET['id']){
        echo '<pre>';
        print_r($row);
        echo '</pre>';
    }
}

此代码会将json转换为数组。由于数组是多维的,因此您需要使用foreach来访问嵌套数组。之后,简单的if就可以完成工作。

http://localhost/scripts/test.php?id=2

这是我正在使用的URL,这是输出:

Array
(
    [id] => 2
    [Name] => Array
        (
            [FirstName] => Mercedes
            [LastName] => Kshlerin
            [FullName] => Dr. Kellie Bashirian
        )

    [Address] => Array
        (
            [Address1] => 12638 Cali Spurs
            [Address2] => Suite 353
            [ZipCode] => 76622
        )

    [Phone] => 319-329-3169 x8848
)