2016-08-15 63 views
1

如果我有下面的JSON,當ID == 6時,如何得到NameAge的值?從特定條件中選擇JSON

[{"Name":" Jim", "ID":"6", "Age": "0"},{"Name":" Bob", "ID":"53", "Age": "0"}] 

我試圖做到這一點,到目前爲止,但我得到了以下錯誤:

Notice: Trying to get property of non-object on line 3

$json = '[{"Name":" Jim", "ID":"6", "Age": "0"},{"Name":" Bob", "ID":"53", "Age": "0"}]'; 
$json2 = json_decode($json); 
if($json2->ID == '6') { 
    echo $json2->Name; 
    echo $json2->Age; 
} 
+0

你唯一缺少的就是foreach循環,在你試圖訪問每個對象的名字和年齡之前,循環遍歷所有對象。 – Rizier123

回答

2

用一個簡單的循環:

$json = '[{"Name":" Jim", "ID":"6", "Age": "0"},{"Name":" Bob", "ID":"53", "Age": "0"}]'; 
$array = json_decode($json); 
foreach($array as $person){ 
    if($person->ID == '6') { 
     echo $person->Name; 
     echo $person->Age; 
    } 
} 

如果您需要訪問更多比陣列中的一個人,創建一個索引在ID上的新數組可能是有意義的:

$json = '[{"Name":" Jim", "ID":"6", "Age": "0"},{"Name":" Bob", "ID":"53", "Age": "0"}]'; 
$array = json_decode($json); 
$indexPeopleArray=[]; 
foreach($array as $person){ 
    $indexPeopleArray[$person->ID]=$person; 
} 

然後,你可以簡單地訪問每個人:

echo $indexPeopleArray[6]->name; //jim 
echo $indexPeopleArray[53]->name; //bob 
+0

謝謝史蒂夫! :) –

1

您可以通過使用

if($json2[0]->ID == '6') { 
    echo $json2[0]->Name; 
    echo $json2[0]->Age; 
} 

//因爲JSON [表示數組得到它。所以當你使用json_decode對它進行解碼時,數組就像這樣創建。

array[0][Name] 
array[0][Age] 
array[0][Age] 

array[1][Name] 
array[1][Age] 
array[1][Age] 

@steve的答案也是正確的。