如何在PHP中访问JSON解码数组

25
我从 javascript 返回了一个 JSON 数据类型的数组到 PHP,使用 json_decode($data, true) 将其转换为关联数组,但当我尝试使用关联 index 时,出现错误 "Undefined index"。返回的数据看起来像这样。
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中访问这样的数组?感谢任何建议。


你可以像访问其他数组一样访问它,因为它就是一个数组。它来自哪里并不重要。如果出现错误,则表示您尝试访问的键不存在。因此,请仔细检查您想要访问的键是否存在。如果您是 PHP 中的新手,请查看文档:http://php.net/manual/en/language.types.array.php。 - Felix Kling
1
你能添加一下你试图访问元素的代码吗?(并且清理一下数组,使其更易读) - Brad
6个回答

69

在上面的例子中,由于您将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..

如果您在调用json_decode时未将第二个参数设置为true,它会将结果返回为一个对象:
echo $myArray[0]->id;

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


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

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

就像这样 :)

当我尝试以那种方式访问时,会出现错误“无法将stdClass对象用作数组”。 - Chibuzo
那么你实际上没有将数据解析为关联数组。请查看我的更新答案。 - Norguard

1
这可能会对您有所帮助!
$latlng='{"lat":29.5345741,"lng":75.0342196}';
$latlng=json_decode($latlng,TRUE); // array
echo "Lat=".$latlng['lat'];
echo '<br/>';
echo "Lng=".$latlng['lng'];
echo '<br/>';



$latlng2='{"lat":29.5345741,"lng":75.0342196}';
$latlng2=json_decode($latlng2); // object
echo "Lat=".$latlng2->lat;
echo '<br/>';
echo "Lng=".$latlng2->lng;
echo '<br/>';

1
由于您将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));

?>

0

当您想要循环遍历多维数组时,可以像这样使用foreach:

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

那么我该如何解码来自 https://api.forecast.io/forecast/... 的每小时数据呢?我已经尝试了所有方法,但无法获取子数组。 - andrebruton
JSON结果的格式是什么?您是使用JavaScript调用服务吗? - the_butterfly_effect

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接