2016-02-26 158 views
2

我有這樣的JSON響應JSON解析PHP的問題

{"success":true,"results":[{"response":["random1"],"id":"6566","Limit":1},{"response":["random2"],"id":"6563","Limit":1},{"response":["random3"],"id":"6568","Limit":1}]} 

所有我需要的是從響應提取random1,random2,隨機,3所以最終的結果將是:

  • random1
  • random2
  • random3

我有此腳本

$jsonData = file_get_contents("json"); 

$json = json_decode($jsonData,true); 

foreach($json["results"][0]["response"] as $data) { 
{ 
    echo json_encode($data); 

} 
} 

但是,這將只提取

  • random1

如果我改變[0][1]將提取random2和[2] random3 如何,我可以得到random1,random2,隨機3,一次迴應?所以最終的迴音是:

  • random1
  • random2
  • random3

預先感謝您,任何幫助,將不勝感激!

回答

3

循環在你$json['result']你做什麼只接收第一指標0具有random1作爲其response

$json = '{"success":true,"results":[{"response":["random1"],"id":"6566","Limit":1},{"response":["random2"],"id":"6563","Limit":1},{"response":["random3"],"id":"6568","Limit":1}]}'; 
$json = json_decode($json,true); 

foreach($json["results"] as $data) { 
    echo $data['response'][0]."\n"; 
} 

試試吧here


更新

如果你想過濾讓我們說random1然後做這樣的

$json = json_decode($json,true); 
$filter = array("random1"); //You can add items to filter 
$result = array(); 
foreach($json["results"] as $data) { 
    if(!in_array($data['response'][0],$filter)) 
     $result[] = $data; 
} 
print_r($result); 

$result將只包含random2 & random3

+0

謝謝你這麼多,這是真正的工作! –

+0

@AlexandruVorobchevici沒問題。很高興我幫了忙。確保接受將來參考的答案,並幫助他人解決同樣的問題。 – roullie

+0

是否有任何更改在此插入詞語過濾器?所以我可以過濾一些我嘗試過的單詞if(strpos($ data,'random1')!== false)但不會工作 –

0

results是一個數組,所以你得到了數組中的第一個由這樣的:$json["results"][0]

如果要遍歷所有的值,它應該是這樣的:

foreach($json["results"] as $data) { 
    echo json_encode($data['response']); 

} 
0
foreach($json["results"] as $data) { echo json_encode($data['response']);}