2013-10-20 38 views
1

我的影片返回JSON,看起來像這樣的API調用:如何在PHP中處理這種類型的返回JSON?

{"subtotal":{"amount":"0.50","currency":"USD"}} 

我不知道如何訪問「量」的變量。我試過

$jsonObject = json_decode(returnJSON); 
$amount = $jsonObject->{'subtotal'}->{'amount'} 

但這不起作用。這些數據如何被訪問?

+0

是'returnJSON'必須包含JSON字符串變量像'$ returnJSON ='{「subtotal」:{「amount」:「0.50」,「currency」:「USD」}}'' – zzlalani

回答

1

試試這個

$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; 
0

什麼不起作用?什麼是錯誤信息?你得到一個

試圖讓非對象的財產mypath中\ myPHPFile第3行

錯誤信息?

在這種情況下,這是因爲你的JSON有缺陷,缺少一個右括號。修復後,它在我身邊工作,以您想要的方式訪問它。

此外,不要忘記用PHP中的分號關閉每一行。

+0

Srsly,downvote?爲了什麼?解決OP問題? οO – ds1

+0

-1。答案不解決OP的問題。 OP正試圖通過訪問它。一些混亂的語法($ jsonObject - > {'subtotal'} - > {'amount'})作者json看起來有瑕疵嗎?你提到的唯一正確的東西是缺少的分號... –

+0

「有一個閉幕支架失蹤」修復,修復了他的問題,是的。編輯:FYI OP在我回答後編輯了缺失的左括號。 – ds1

1

至於反對所有這些其他意見,你也可以把它當作一個普通的對象(這是json_decode的默認):

$jsonObject = json_decode($returnJSON); 
$amount = (float)$jsonObject->subtotal->amount; 

var_dump($amount); //float(0.50) 
+0

使用對象語法的+1。json_decode($ json,true);用於assoc數組。 另外我認爲這將是很好的解釋爲什麼你添加了一個類型轉換 –

相關問題