LoginSignup
8
8

More than 5 years have passed since last update.

PHPのjson_encode=>json_decodeで空連想配列が配列に変換される現象

Posted at

PHPでJSONを扱う場合、json_decode()の第二引数にtrueを指定して配列として扱う場合がよくあると思います。
これを使っていると json_encode()してjson_decode()で戻すと、空連想配列(stdClass)が配列になってしまうようです。
memcachedなんかにJSONで配列を保存しているような場合には注意ですね。
キャッシュ時と非キャッシュ時で異なる形式のJSONをクライアントに返してしまうなんてことが起こってしまいます。

ソース

$r = array('hoge'=> new \stdClass());
$j = json_encode($r);
echo $j . "\n";
print_r(json_decode($j,true));
echo "\n";

結果

{"hoge":{}}
Array
(
    [hoge] => Array
        (
        )

)
8
8
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8