4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[PHP]json_decodeで返される値の扱い方

Posted at

PHPのjson_decode()について忘備録。
第二引数に指定した値によって型が変わる。

json_decode($json, true); //返される型は連想配列形式
json_decode($json, false); //返される型はobject形式
json_decode($json); //JSON_OBJECT_AS_ARRAYが設定されているかどうかによって決まる

連想配列形式

第二引数がtrueの場合、型は連想配列。

$json = '{"foo":1,"bar":2,"foo-bar":3}';

$result = json_decode($json, true);

echo(gettype($result)); // array

中の値を取り出す場合は配列のキーを指定して呼び出す。

$result["foo"];

オブジェクト形式

第二引数がfalseの場合、型はobject(stdClass)。

$json = '{"foo":1,"bar":2,"foo-bar":3}';

$result = json_decode($json, false);

echo(gettype($result)); // object

中の値を取り出す場合はオブジェクトプロパティを呼び出す。

$result->foo;

// PHPの命名規約では使えないハイフンなどの文字を含む要素にアクセスするには、要素名を波括弧とアポストロフィで囲む
$result->{'foo-bar'};
4
0
0

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
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?