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

2022-08-30 16:50:27

我从 to 返回了一个数据类型数组,我曾经将其转换为关联数组,但是当我尝试使用关联数组使用它时,我得到错误 返回的数据看起来像这样JSONjavascriptPHPjson_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


答案 1

在上面的示例中,当您将第二个参数传递给 时,您可以检索数据,执行类似于以下内容的操作:truejson_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..

如果不将第二个参数传递给它,则会将其作为对象返回:truejson_decode

echo $myArray[0]->id;

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


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

推荐