简体   繁体   中英

How to access JSON decoded array in PHP

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" }  

Please, how do I access such array in PHP ? Thanks for any suggestion.

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..

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;
$data = json_decode($json, true);
echo $data[0]["c_name"]; // "John"


$data = json_decode($json);
echo $data[0]->c_name;      // "John"
$data = json_decode(...);
$firstId = $data[0]["id"];
$secondSeatNo = $data[1]["seat_no"];

Just like this :)

As you're passing true as the second parameter to json_decode , in the above example you can retrieve data doing something similar to:

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

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

?>

When you want to loop into a multiple dimensions array, you can use foreach like this:

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

This may help you!

$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/>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM