Help us understand the problem. What is going on with this article?

phpのjson_encodeでjsonの形式を空配列と空のオブジェクトで識別するオプション

phpでjsonの形式にエンコードする際に連想配列を用いていることが多いと思いますが、
空の配列の場合はどうなるでしょう。

普通にデフォルトで指定するとこうなります

$a = [];

var_dump(json_encode($a));
出力結果
string(2) "[]"

あれ?jsonって{}になるんじゃないの?って思った方もいると思います。
そこのjsonの形式を変更させるオプションがJSON_FORCE_OBJECTです。

これを使うと空配列[]ではなく{}と変換されます。

JSON_FORCE_OBJECTを指定した場合とデフォルトの場合

$a = [];

var_dump(json_encode($a));
var_dump(json_encode($a, JSON_FORCE_OBJECT));
出力結果
string(2) "[]"
string(2) "{}"

JSON_FORCE_OBJECTパラメータはphp5.3.0からoptionsパラメータに追加されました。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした