我有一个 API 调用,它返回的 JSON 如下所示:
{"subtotal":{"amount":"0.50","currency":"USD"}}
我不确定如何访问"金额"变量。我试过了
$jsonObject = json_decode(returnJSON);
$amount = $jsonObject->{'subtotal'}->{'amount'}
但这行不通。如何访问这些数据?
您可以将其作为关联数组访问:
$jsonObject = json_decode($returnJSON, true);
$amount = $jsonObject['subtotal']['amount'];
http://php.net/manual/en/function.json-decode.php
试试这个
$returnJSON = '{"subtotal":{"amount":"0.50","currency":"USD"}}';
$jsonObject = json_decode($returnJSON, true);
$amount = $jsonObject['subtotal']['amount'];
或
$returnJSON = '{"subtotal":{"amount":"0.50","currency":"USD"}}';
$jsonObject = json_decode($returnJSON);
$amount = $jsonObject->subtotal->amount;
与所有这些其他注释相反,您也可以将其用作常规对象(这是json_decode
的默认值):
$jsonObject = json_decode($returnJSON);
$amount = (float)$jsonObject->subtotal->amount;
var_dump($amount); //float(0.50)
你需要的就在这里:
http://php.net/manual/en/function.json-decode.php#example-3736
检查第一个示例。
什么不起作用?错误消息是什么?你得到一个
尝试在第 3 行获取 MyPath''myPHPFile 中非对象的属性
错误信息?
在这种情况下,这是因为您的 JSON 有缺陷,缺少一个右括号。修复后,它可以在我这边以您想要的方式访问它。
另外,不要忘记在 PHP 中用分号结束每一行。