I am trying to decode a JSON string into an array but i get the following error.
Fatal error: Cannot use object of type stdClass as array in C:\\w
json_decode($data, true); // Returns data in array format
json_decode($data); // Returns collections
So, If want an array than you can pass the second argument as 'true' in json_decode
function.
in PHP json_decode convert json data into PHP associated array
For Ex: $php-array= json_decode($json-data, true);
print_r($php-array);
I hope this will help you
$json_ps = '{"courseList":[
{"course":"1", "course_data1":"Computer Systems(Networks)"},
{"course":"2", "course_data2":"Audio and Music Technology"},
{"course":"3", "course_data3":"MBA Digital Marketing"}
]}';
Use Json decode function
$json_pss = json_decode($json_ps, true);
Looping over JSON array in php
foreach($json_pss['courseList'] as $pss_json)
{
echo '<br>' .$course_data1 = $pss_json['course_data1']; exit;
}
Result: Computer Systems(Networks)
try this
$json_string = 'http://www.domain.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
echo "<pre>";
print_r($obj);
Just in case you are working on php less then 5.2 you can use this resourse.
http://techblog.willshouse.com/2009/06/12/using-json_encode-and-json_decode-in-php4/
http://mike.teczno.com/JSON/JSON.phps
json_decode
support second argument, when it set to TRUE
it will return an Array
instead of stdClass Object
. Check the Manual page of json_decode
function to see all the supported arguments and its details.
For example try this:
$json_string = 'http://www.example.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, TRUE); // Set second argument as TRUE
print_r($obj['Result']); // Now this will works!