如何将 json 响应转换为 php 对象


How to convert json respone into php object?

下面是我的json响应,我正在使用json_decode转换php object的响应,"状态"和"msg"转换成功,但问题出在"amt"上。如何在 php 对象中获取"amt"? $amt=$response->transaction_details['amt'];不起作用。

响应:

{"status":1,"msg":"已成功获取事务","transaction_details":{"686868686505":{"payid":"293642892","amt":"10.00","txnid":"686868686505","additional_charges":"0.00","productinfo":"SHIRT","firstname":"WILLIAM

}}}

法典:

$response = json_decode($o,true);
$msg = $response['msg']; 
$status = $response['status'];
$amt=$response->transaction_details->['amt'];
echo '<br>';
echo $amt;
echo '<br>';
echo $msg;
echo '<br>';
echo $status;

输出:

已成功
获取的事务1

你正在将数组与对象混合在一起。

json_decode第二个参数将允许您获取 JSON 对象或 JSON 数组,如果为 null 或 false,它将返回 json 对象,如果将第二个参数设置为 true 或任何转换为 true 的参数,它将返回 JSON 数组。

请参阅 php.net 中的文档

因此,您需要将其更改为:

$response = json_decode($o); // or json_decode($o, false);
$msg = $response->msg; 
$status = $response->status;
//since you use all numbers for json property, I'll assume this would fail
$amt=$response->transaction_details->686868686505->amt;
echo '<br>';
echo $amt;
echo '<br>';
echo $msg;
echo '<br>';
echo $status;

或者如果你喜欢使用数组

$response = json_decode($o,true);
$msg = $response['msg']; 
$status = $response['status'];
$amt=$response['transaction_details']['686868686505']['amt'];
echo '<br>';
echo $amt;
echo '<br>';
echo $msg;
echo '<br>';
echo $status;