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

前端之家收集整理的这篇文章主要介绍了如何在PHP中访问JSON解码的数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我从 javascriptPHP返回了JSON数据类型的数组,我使用json_decode($data,true)将其转换为关联数组,但是当我尝试使用关联索引使用它时,我得到错误“Undefined index”返回的数据看起来像这样
  1. 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" }
  2. [1]=> array(4) { ["id"]=> string(3) "599" ["c_name"]=> string(6) "George" ["next_of_kin"]=> string(7) "6544539" ["seat_no"]=> string(1) "2" }
  3. [2]=> array(4) { ["id"]=> string(3) "601" ["c_name"]=> string(5) "Emeka" ["next_of_kin"]=> string(10) "5457394839" ["seat_no"]=> string(1) "9" }
  4. [3]=> array(4) { ["id"]=> string(3) "603" ["c_name"]=> string(8) "Chijioke" ["next_of_kin"]=> string(9) "653487309" ["seat_no"]=> string(1) "1" }

请问如何在PHP中访问这样的数组?感谢任何建议.

当你作为第二个参数传递给json_decode时,在上面的例子中,您可以检索类似于以下内容的数据:
  1. $myArray = json_decode($data,true);
  2. echo $myArray[0]['id']; // Fetches the first ID
  3. echo $myArray[0]['c_name']; // Fetches the first c_name
  4. // ...
  5. echo $myArray[2]['id']; // Fetches the third ID
  6. // etc..

如果没有将第二个参数传递给json_decode,那么它将返回它作为一个对象:

  1. echo $myArray[0]->id;

猜你在找的PHP相关文章