从 JSON 数据中获取特定值

时间:2021-04-05 04:01:03

标签: php json

我想从 json 中获取特定的数据值。这是我的json代码

{"status":{"shipmentnumber":"5014402092","statusrow":[{"statusdate":"Mar 01st, 2021","statustime":"04:51 PM","statusmessage":"Delivered to "},{"statusdate":"Mar 01st, 2021","statustime":"07:08 AM","statusmessage":"Shipment has reached blueEX Gujranwala - Gujranwala"},{"statusdate":"Feb 26th, 2021","statustime":"10:43 PM","statusmessage":"Shipment is on route to Gujranwala"},{"statusdate":"Feb 26th, 2021","statustime":"10:42 PM","statusmessage":"Shipment reached blueEX Karachi Warehouse, Karachi"},{"statusdate":"Feb 26th, 2021","statustime":"03:36 PM","statusmessage":"Order information received, pending at Shipper's end."}]}}

我想获得“statusmessage”:“Delivered to”数据。这是我的代码

$data['status']['statusrow'][0]['statusmessage']

但它只返回 {。

有人请指导我做错了什么

2 个答案:

答案 0 :(得分:2)

您如何将 JSON 字符串转换为 PHP 数据结构?

这对我有用:

$json = '{"status":{"shipmentnumber":"5014402092","statusrow":[{"statusdate":"Mar 01st, 2021","statustime":"04:51 PM","statusmessage":"Delivered to "},{"statusdate":"Mar 01st, 2021","statustime":"07:08 AM","statusmessage":"Shipment has reached blueEX Gujranwala - Gujranwala"},{"statusdate":"Feb 26th, 2021","statustime":"10:43 PM","statusmessage":"Shipment is on route to Gujranwala"},{"statusdate":"Feb 26th, 2021","statustime":"10:42 PM","statusmessage":"Shipment reached blueEX Karachi Warehouse, Karachi"},{"statusdate":"Feb 26th, 2021","statustime":"03:36 PM","statusmessage":"Order information received, pending at Shipper\'s end."}]}}';
$data = json_decode( $json );

echo $data->status->statusrow[0]->statusmessage; // "Delivered to"

答案 1 :(得分:0)

$data = '{"status":{"shipmentnumber":"5014402092","statusrow":[{"statusdate":"Mar 01st, 2021","statustime":"04:51 PM","statusmessage":"Delivered to "},{"statusdate":"Mar 01st, 2021","statustime":"07:08 AM","statusmessage":"Shipment has reached blueEX Gujranwala - Gujranwala"},{"statusdate":"Feb 26th, 2021","statustime":"10:43 PM","statusmessage":"Shipment is on route to Gujranwala"},{"statusdate":"Feb 26th, 2021","statustime":"10:42 PM","statusmessage":"Shipment reached blueEX Karachi Warehouse, Karachi"},{"statusdate":"Feb 26th, 2021","statustime":"03:36 PM","statusmessage":"Order information received, pending at Shippers end."}]}}';


$data = json_decode($data,true);
// print_r($data)
echo $data['status']['statusrow'][0]['statusmessage'];