json_encode/json_decode - returns stdClass instead of Array in PHP


Question

Observe this little script:

$array = array('stuff' => 'things');
print_r($array);
//prints - Array ( [stuff] => things )
$arrayEncoded = json_encode($array);
echo $arrayEncoded . "<br />";
//prints - {"stuff":"things"}
$arrayDecoded = json_decode($arrayEncoded);
print_r($arrayDecoded);
//prints - stdClass Object ( [stuff] => things )

Why does PHP turn the JSON Object into a class?

Shouldn't an array that is json_encoded then json_decoded yield the EXACT same result?

1
102
10/4/2012 8:49:07 AM

Accepted Answer

Take a closer look at the second parameter of json_decode($json, $assoc, $depth) at https://secure.php.net/json_decode

139
9/2/2018 1:52:35 PM

$arrayDecoded = json_decode($arrayEncoded, true);

gives you an array.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon