Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access JSON decoded array in PHP

Tags:

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.

like image 497
Chibuzo Avatar asked Feb 23 '13 18:02

Chibuzo


People also ask

How can access JSON decoded data in PHP?

PHP - Accessing the Decoded Values$obj = json_decode($jsonobj);

How can I get JSON encoded data in PHP?

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.

What is JSON decode in PHP?

The json_decode() function is used to decode or convert a JSON object to a PHP object.

Does json_decode return an array?

json_decode support second argument, when it set to TRUE it will return an Array instead of stdClass Object .


2 Answers

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; 
like image 194
juco Avatar answered Oct 19 '22 15:10

juco


$data = json_decode($json, true); echo $data[0]["c_name"]; // "John"   $data = json_decode($json); echo $data[0]->c_name;      // "John" 
like image 27
Norguard Avatar answered Oct 19 '22 16:10

Norguard