我的影片返回JSON,看起來像這樣的API調用:如何在PHP中處理這種類型的返回JSON?
{"subtotal":{"amount":"0.50","currency":"USD"}}
我不知道如何訪問「量」的變量。我試過
$jsonObject = json_decode(returnJSON);
$amount = $jsonObject->{'subtotal'}->{'amount'}
但這不起作用。這些數據如何被訪問?
我的影片返回JSON,看起來像這樣的API調用:如何在PHP中處理這種類型的返回JSON?
{"subtotal":{"amount":"0.50","currency":"USD"}}
我不知道如何訪問「量」的變量。我試過
$jsonObject = json_decode(returnJSON);
$amount = $jsonObject->{'subtotal'}->{'amount'}
但這不起作用。這些數據如何被訪問?
您可以訪問它作爲一個關聯數組:
$jsonObject = json_decode($returnJSON, true);
$amount = $jsonObject['subtotal']['amount'];
試試這個
$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;
什麼不起作用?什麼是錯誤信息?你得到一個
試圖讓非對象的財產mypath中\ myPHPFile第3行
錯誤信息?
在這種情況下,這是因爲你的JSON有缺陷,缺少一個右括號。修復後,它在我身邊工作,以您想要的方式訪問它。
此外,不要忘記用PHP中的分號關閉每一行。
至於反對所有這些其他意見,你也可以把它當作一個普通的對象(這是json_decode
的默認):
$jsonObject = json_decode($returnJSON);
$amount = (float)$jsonObject->subtotal->amount;
var_dump($amount); //float(0.50)
使用對象語法的+1。json_decode($ json,true);用於assoc數組。 另外我認爲這將是很好的解釋爲什麼你添加了一個類型轉換 –
是'returnJSON'必須包含JSON字符串變量像'$ returnJSON ='{「subtotal」:{「amount」:「0.50」,「currency」:「USD」}}'' – zzlalani