2016-07-25 71 views
-2

我有一個JSON文件(test.json),這是JSON的foreach只得到第一個結果出來一個數組

{ 
    "fruit": [{ 
     "id": 364823, 
     "name": "Lemon", 
     "amount": [33], 
     "profile": "http://google.com", 
     "buyid": 5 
    }, { 
     "id": 367851, 
     "name": "Orange", 
     "amount": [69, 95, 166], 
     "profile": "http://google.com", 
     "buyid": 3 
    },{ 
     "id": 35647, 
     "name": "Apple", 
     "amount": [77, 43], 
     "profile": "http://google.com", 
     "buyid": 31 
    } ] 
} 

那麼我有我的PHP腳本來呼應

$url="test.json"; 
    $json = file_get_contents($url); 
    $json = json_decode($json, true); 
    $names = array(); 
    foreach($json['fruit'][0]['amount'] as $val) 
{ 
    echo $val . " <br> "; 
} 

它返回

33 

我怎樣才能得到它返回?

33 
69 95 166 
77 43 

我可以得到它與其他工作一樣ID輪廓buyid但不是這個數組

+1

爲什麼 「JavaScript的」 標籤?關於你的要求,你不需要嵌套循環嗎? – nnnnnn

+0

'['fruit'] [0] ['amount']'數組只有一個元素''amount':' –

+0

或者在第一級添加另一個指向'amount'或implode的'foreach'維度 – Ghost

回答

3
foreach($json['fruit'] as $fruit){ 
    echo implode(' ',$fruit['amount']); 
} 

Live demo

+0

工作過,謝謝! – C0ft

+0

不客氣:-)如果它解決了你的問題,不要忘記選擇這個答案。 – BeetleJuice

相關問題