如何在PHP中访问JSON解码数组 [英] How to access JSON decoded array in PHP
问题描述
我从javascript
到PHP
返回了一个JSON
数据类型的数组,我使用json_decode($data, true)
将其转换为关联数组,但是当我尝试使用关联index
使用它时,我收到错误"Undefined index"
返回的数据如下:
I returned an array of JSON
data type from javascript
to PHP
, I used json_decode($data, true)
to convert it to an associative array, but when I try to use it using the associative index
, I get the error "Undefined index"
The returned data looks like this
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
中访问这样的数组?感谢您的任何建议.
Please, how do I access such array in PHP
? Thanks for any suggestion.
推荐答案
当您将true
作为第二个参数传递给json_decode
时,在上面的示例中,您可以检索类似于以下内容的数据:
As you're passing true
as the second parameter to json_decode
, in the above example you can retrieve data doing something similar to:
$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
,则会将其作为对象返回:
If you do NOT pass true
as the second parameter to json_decode
it would instead return it as an object:
echo $myArray[0]->id;
这篇关于如何在PHP中访问JSON解码数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!