ChatGPT解决这个技术问题 Extra ChatGPT

json_decode to array

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:\wamp\www\temp\asklaila.php on line 6

Here is the code:

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

$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata);
print_r($obj['Result']);
?>
It would have worked if you accessed with $ob->Result instead.

A
AbraCadaver

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);

It begs the question, what are the advantages of having it return as an array and not an object?
It raises the question. To "beg a question" means to assume something that remains to be proved (ref). 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 The default implementation that returns an object could beg the question that objects are better return values than arrays, could it not?
Indeed it could @DavidMann. Touché!
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.
P
Pang

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);

n
neokio

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.


A
Anuj Pandey
A
Arosha De Silva

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

c
coreyavis

This will also change it into an array:

<?php
    print_r((array) json_decode($object));
?>

This a waste of CPU/Memory, as suggested json_decode($object, true); the true does exactly the same, internally much faster.
@TCB13 except if you need both and don't want to run decode again
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.
B
Bugs

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!

A
Avinash Singh
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.


P
Pavan Kumar

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)


S
Salman Mohammad

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


D
Dipali Sakle Systematix

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']);
?>

l
lalithkumar

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
}