【问题标题】:Trying to get property name and id of laravel payload试图获取 laravel 有效负载的属性名称和 id
【发布时间】:2021-07-02 01:33:25
【问题描述】:

我在下面有这个 JSON 有效负载,并希望从有效负载中获取名称和 ID。但是,l 不能从有效负载中反对名称和 ID。

解码 JSON

 $result = json_decode($resp->getBody()->getContents(), true);
                return response()->json(
                    [
    
                        "code" => 200,
                        "message" => "OK",
                        "payload"=>  $result['payload'] ?? '',
                    ]);

API json 有效负载

{
    "code": 200,
    "message": "OK",
    "payload": {
        "items": [
            {
                "name": "Hostel",
                "image": {
                    "name": "WEWEBBFC791FD50E347BD.jpeg"
                },
                "rate": {
                    "amount": "3.0000",
                    "currency": {
                        "code": "US"
                    }
                },
                "pricing": [
                    {
                        "rate": "3.0000"
                    }
                ],
                "id": 12, // get this id
                "created_at": "2021-02-28T11:08:25+00:00"
            }
            ..........
        ],
        "total": 10,
        "offset": 10
    }
}

【问题讨论】:

    标签: php json laravel api


    【解决方案1】:

    使用 json_decode 将 json 解码为关联数组,然后像访问任何其他关联数组一样访问该数组的元素。

    您的集合中似乎可以有一个或多个items,因此您需要使用循环来迭代它们。

    $decoded = json_decode($json, true);
    
    foreach ($decoded['payload']['items'] as $item) {
        $name = $items['name'];
        $id = $items['id'];
    
        dump($name, $id);
    }
    
    

    【讨论】:

      猜你喜欢
      • 2019-12-13
      • 2021-07-29
      • 2021-06-04
      • 2020-09-28
      • 2021-05-26
      • 2021-06-05
      • 2020-06-26
      • 2018-07-03
      • 1970-01-01
      相关资源
      最近更新 更多