2013-02-23 22 views
12

我回到JSON數據類型的數組從javascriptPHP,我用json_decode($data, true)將其轉換爲一個關聯數組,但是當我嘗試使用關聯index使用它,我得到的錯誤"Undefined index"返回的數據看起來像這樣如何訪問JSON解碼的數組中的PHP

array(14) { [0]=> array(4) { ["id"]=> string(3) "597" ["c_name"]=> string(4) "John" ["next_of_kin"]=> string(10) "5874594793" ["seat_no"]=> string(1) "4" } 
[1]=> array(4) { ["id"]=> string(3) "599" ["c_name"]=> string(6) "George" ["next_of_kin"]=> string(7) "6544539" ["seat_no"]=> string(1) "2" } 
[2]=> array(4) { ["id"]=> string(3) "601" ["c_name"]=> string(5) "Emeka" ["next_of_kin"]=> string(10) "5457394839" ["seat_no"]=> string(1) "9" } 
[3]=> array(4) { ["id"]=> string(3) "603" ["c_name"]=> string(8) "Chijioke" ["next_of_kin"]=> string(9) "653487309" ["seat_no"]=> string(1) "1" } 

請,我怎麼訪問PHP這樣的陣列?感謝您的任何建議。

+0

您像訪問其他任何數組一樣訪問它,因爲它就是這樣一個數組。它來自哪裏並不重要。如果出現錯誤,則表示您嘗試訪問的密鑰不存在。所以,仔細檢查你想訪問的密鑰是否存在。如果您是PHP新手,請查看以下文檔:http://php.net/manual/en/language.types.array.php。 – 2013-02-23 18:27:06

+1

你可以在你試圖訪問元素的地方添加代碼嗎? (並清理數組,使其更易於閱讀) – Brad 2013-02-23 18:27:10

回答

48

當你傳遞true作爲第二個參數來json_decode,你可以檢索數據做類似的事情,以上面的例子:

$myArray = json_decode($data, true); 
echo $myArray[0]['id']; // Fetches the first ID 
echo $myArray[0]['c_name']; // Fetches the first c_name 
// ... 
echo $myArray[2]['id']; // Fetches the third ID 
// etc.. 

如果您不通過true作爲json_decode的第二個參數,它會將其作爲對象返回:

echo $myArray[0]->id; 
3
$data = json_decode(...); 
$firstId = $data[0]["id"]; 
$secondSeatNo = $data[1]["seat_no"]; 

就這樣:)

+0

當我嘗試以這種方式訪問​​時,出現錯誤「無法將類型爲stdClass的對象用作數組」。 – Chibuzo 2013-02-23 18:33:35

+0

然後你實際上並沒有將數據解析爲關聯數組。看到我更新的答案。 – Norguard 2013-02-23 18:39:48

7
$data = json_decode($json, true); 
echo $data[0]["c_name"]; // "John" 


$data = json_decode($json); 
echo $data[0]->c_name;  // "John" 
0

當要循環到多個維度陣列,可以使用的foreach這樣的:

foreach($data as $users){ 
    foreach($users as $user){ 
     echo $user['id'].' '.$user['c_name'].' '.$user['seat_no'].'<br/>'; 
    } 
} 
+0

然後,我將如何解碼來自https://api.forecast.io/forecast/...的每小時數據?我嘗試了一切,但無法獲得子陣列 – andrebruton 2014-07-23 19:09:08

+0

json結果的格式是什麼?你打電話使用JavaScript的服務? – 2014-08-15 17:15:08

0

如你作爲第二個參數傳遞true到json_decode,在上述例子中,你可以檢索類似於以下內容的數據:

<?php 
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; 

var_dump(json_decode($json)); 
var_dump(json_decode($json, true)); 

?>