2017-04-14 89 views
2

我試圖訪問具有與多維JSON輸入的API,這是陣列回聲多維JSON和PHP

[{ 
"Value 1":"a", 
"Value 2": 
    { 
     "Value 3": 
     { 
      "Value4":11, 
      "Value5":"C", 
     }, 
     "Value 4": 
     { 
      "Value6":12, 
     } 
    } 
}] 

欲呼應「11」值4和「12」中Value6。我已經嘗試呼應它

$varkota = 'url to json output'; 
$datakota = json_decode(file_get_contents($varkota, true)); 
$data1 = json_decode($datakota[0]->Value2); 
$data2 = json_decode($data1[0]->Value3); 
echo $data2[0]->Value4; 

錯誤告訴我:

!) SCREAM: Error suppression ignored for 
(!) Warning: json_decode() expects parameter 1 to be string, object given in debug.php on line 6 
Call Stack 
# Time Memory Function Location 
1 0.0020 145280 {main}() ..\debug.php:0 
2 4.1329 188648 json_decode () ..\debug.php:6 

(!) SCREAM: Error suppression ignored for 
(!) Notice: Trying to get property of non-object in debug.php on line 7 
Call Stack 
# Time Memory Function Location 
1 0.0020 145280 {main}() ..\debug.php:0 

(!) SCREAM: Error suppression ignored for 
(!) Notice: Trying to get property of non-object in on line 8 
Call Stack 
# Time Memory Function Location 
1 0.0020 145280 {main}() ..\debug.php:0 

任何想法?

+0

我無法驗證您的JSON字符串'錯誤:在第6行解析錯誤: ... \t \t \t「Value5」:「C」,\t \t},\t \t「Value 4」:{\t \t ----------------------^ 期待'STRING',得到'}'' – vietnguyen09

+0

@RohanKumar編輯 –

+0

@YudhistiraBayu json有錯誤。 「Value5」:「C」,最後一個鍵不允許使用逗號。 –

回答

3

首先,你需要使用json_decode只有一次,而你的密鑰具有被有空間空間和鍵,那麼你需要附上它作爲字符串和{}。試着像,

$datakota = json_decode(file_get_contents($varkota, true)); 
$data1 = $datakota[0]->{'Value 2'}; 
$data2 = $data1->{'Value 3'}; // no need to use array [0], as Value 2 is object 
echo $data2->Value4; // no need to use array [0], as Value 3 is also an object 

在單行線,只把它作爲

echo $datakota[0]->{'Value 2'}->{'Value 3'}->Value4; 

Online Demo

+0

謝謝!解決了! –

1

您只需要撥打json_decode一次。

$varkota = 'url to json output'; 
$datakota = json_decode(file_get_contents($varkota, true)); 
$data1 = $datakota[0]->Temperature->Metric; 
// ... 

或與您當前的JSON字符串

$data1 = $datakota[0]->{"Value 2"}->{"Value 3"}; 
+0

謝謝,解決了! –

+0

@RohanKumar他改變了這個問題.. – Philipp

+0

我沒有看到問題揭幕戰的好處,但我添加了一個替代結構的變化.. – Philipp