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.
PHP - Accessing the Decoded Values$obj = json_decode($jsonobj);
To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.
The json_decode() function is used to decode or convert a JSON object to a PHP object.
json_decode support second argument, when it set to TRUE it will return an Array instead of stdClass Object .
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With