I have this JSON payload below and want to get names and ids from the payload. However, l cannot object names and ids from the payload.
Decode JSON
$result = json_decode($resp->getBody()->getContents(), true); return response()->json( [ "code" => 200, "message" => "OK", "payload"=> $result['payload'] ?? '', ]);
Api json payloads
{ "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 } }
Advertisement
Answer
Use json_decode
to decode the json to an associative array, then access the elements of the array as you would any other assoc array.
It looks as though you can have one or more items
in your collection, so you’ll want to use a loop to iterate over them.
$decoded = json_decode($json, true); foreach ($decoded['payload']['items'] as $item) { $name = $items['name']; $id = $items['id']; dump($name, $id); }