486

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

Here is the code:

$json_string = 'http://www.example.com/jsondata.json';

$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata);
print_r($obj['Result']);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Harsha M V
  • 54,075
  • 125
  • 354
  • 529

12 Answers12

967

As per the documentation, you need to specify true as the second argument if you want an associative array instead of an object from json_decode. This would be the code:

$result = json_decode($jsondata, true);

If you want integer keys instead of whatever the property names are:

$result = array_values(json_decode($jsondata, true));

However, with your current decode you just access it as an object:

print_r($obj->Result);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
Stephen
  • 18,597
  • 4
  • 32
  • 33
  • 4
    It begs the question, what are the advantages of having it return as an array and not an object? – Foxinni Aug 16 '12 at 13:31
  • 62
    It raises the question. To "beg a question" means to assume something that remains to be proved ([ref](http://en.wikipedia.org/wiki/Begging_the_question)). In either case, the advantage might be that the OP is more comfortable traversing arrays than objects, or that some other, already implemented, code requires an array. – jamesnotjim Mar 06 '13 at 15:31
  • 8
    @jamesnotjim The default implementation that returns an object could beg the question that objects are better return values than arrays, could it not? – David Mann Nov 13 '13 at 02:43
  • 7
    Indeed it could @DavidMann. Touché! – jamesnotjim Nov 13 '13 at 18:53
  • 9
    I would add the comment (albeit years later) that there is no possibility of JSON containing anything but data making this a confounding "default" choice. – Barry Jul 25 '16 at 16:13
  • What do you mean? It's an option about whether you get the json objects with string keys presented as php objects of stdClass or associative arrays. – Stephen Jul 25 '16 at 16:31
  • perform statement $array = array_values($array); if you want indexed array insted of associative one. – Kiran Maniya Jan 25 '19 at 06:18
  • 1
    JSON is Javascript _Object_ Notation, and it describes data objects. I suppose that is the rationale behind the default choice. I agree, however, that an associative array is often more useful in PHP. It's just not a thing that exists in terms of JS/JSON. – Steen Schütt Oct 17 '19 at 11:21
  • Old post but this totally helped me out! – Martin Oct 21 '21 at 21:55
49

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);
Pang
  • 9,564
  • 146
  • 81
  • 122
xkeshav
  • 53,360
  • 44
  • 177
  • 245
30

This is a late contribution, but there is a valid case for casting json_decode with (array).
Consider the following:

$jsondata = '';
$arr = json_decode($jsondata, true);
foreach ($arr as $k=>$v){
    echo $v; // etc.
}

If $jsondata is ever returned as an empty string (as in my experience it often is), json_decode will return NULL, resulting in the error Warning: Invalid argument supplied for foreach() on line 3. You could add a line of if/then code or a ternary operator, but IMO it's cleaner to simply change line 2 to ...

$arr = (array) json_decode($jsondata,true);

... unless you are json_decodeing millions of large arrays at once, in which case as @TCB13 points out, performance could be negatively effected.

designosis
  • 5,182
  • 1
  • 38
  • 57
6

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

Anuj Pandey
  • 938
  • 2
  • 11
  • 30
6

According to the PHP Documentation json_decode function has a parameter named assoc which convert the returned objects into associative arrays

 mixed json_decode ( string $json [, bool $assoc = FALSE ] )

Since assoc parameter is FALSE by default, You have to set this value to TRUE in order to retrieve an array.

Examine the below code for an example implication:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));

which outputs:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}
Arosha De Silva
  • 597
  • 8
  • 18
5

This will also change it into an array:

<?php
    print_r((array) json_decode($object));
?>
coreyavis
  • 87
  • 1
  • 7
  • 6
    This a waste of CPU/Memory, as suggested `json_decode($object, true);` the `true` does exactly the same, internally much faster. – TCB13 Dec 12 '13 at 00:13
  • 1
    @TCB13 except if you need both and don't want to run decode again – Jimmy Kane Jan 21 '15 at 10:26
  • 3
    Concur with @JimmyKane . I tried and run both versions in a cycle; if you need both object and array (albeit this ought to happen rarely?), `json_decode` + casting is 45% faster than running both flavours of `json_decode`. On the other hand, both are so fast that unless you need literally *thousands* of decodings, the difference is negligible. – LSerni May 29 '15 at 10:35
5
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.

Avinash Singh
  • 4,970
  • 8
  • 20
  • 35
Shanu Singh
  • 101
  • 2
  • 2
4

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!
Bugs
  • 4,491
  • 9
  • 32
  • 41
Arjun Kariyadan
  • 489
  • 2
  • 12
4

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)

Pavan Kumar
  • 164
  • 15
Solomon Suraj
  • 1,162
  • 8
  • 8
2

in PHP json_decode convert json data into PHP associated array
For Ex: $php-array= json_decode($json-data, true); print_r($php-array);

Salman Mohammad
  • 182
  • 1
  • 14
2

Please try this

<?php
$json_string = 'http://www.domain.com/jsondata.json';

$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, true);
echo "<pre>"; print_r($obj['Result']);
?>
2

Try like this:

$json_string = 'https://example.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata);
print_r($obj->Result);
foreach($obj->Result as $value){
  echo $value->id; //change accordingly
}
lalithkumar
  • 3,480
  • 4
  • 24
  • 40