はじめに
PHPでデータを扱う際、配列やオブジェクトをJSON形式に変換する場面は多くあります。
特にAPI連携や外部サービスとの通信で頻出するのが json_encode()
と json_decode()
。
PHP8上級試験でも「引数 $associative
の扱い」や「型変換の結果」がよく問われるポイントです。
この記事では、実際の出力結果を確認しながら両者の動作を整理します。
目次
🧩 json_encode()とは?
PHPの値(配列・オブジェクトなど)を JSON形式の文字列 に変換する関数です。
json_encode(mixed $value, int $flags = 0, int $depth = 512): string|false
$value
: エンコード対象の値(配列、オブジェクト、スカラーなど)$flags
: 特殊な変換オプション(例:JSON_PRETTY_PRINT
など)$depth
: 再帰的にエンコードする最大深度- 返り値: 成功時は JSON文字列、失敗時は
false
🔁 json_decode()とは?
JSON文字列を PHPの値に戻す(デコードする) 関数です。
json_decode(
string $json,
?bool $associative = null,
int $depth = 512,
int $flags = 0
): mixed
$json
: JSON形式の文字列$associative
:true
→ 連想配列で返すfalse
または省略 → stdClassオブジェクトで返す
🧪 実行例で確認
<?php
declare(strict_types=1);
error_reporting(-1);
$datum = [
'num' => 123,
'str' => 'hello',
'bool' => true,
'null' => null,
];
var_dump($datum);
$js = json_encode($datum);
var_dump($js);
$datum2 = json_decode($js, true);
var_dump($datum2);
▶ 実行結果
array(4) {
["num"]=>
int(123)
["str"]=>
string(5) "hello"
["bool"]=>
bool(true)
["null"]=>
NULL
}
string(49) "{"num":123,"str":"hello","bool":true,"null":null}"
array(4) {
["num"]=>
int(123)
["str"]=>
string(5) "hello"
["bool"]=>
bool(true)
["null"]=>
NULL
}
🧠 図解:エンコードとデコードの流れ
PHP配列
↓ json_encode()
JSON文字列
↓ json_decode(true)
PHP連想配列
✅ 試験対策ポイントまとめ
ポイント | 内容 |
---|---|
json_encode() | PHP → JSON文字列に変換 |
json_decode() | JSON → PHPの値に戻す |
$associative 引数 | true で配列、false でオブジェクト |
null / bool / 数値の扱い | JSONリテラルとしてそのまま変換される |
エラー確認 | json_last_error() / json_last_error_msg() で確認可 |
💡 応用例:オブジェクトとしてデコードする場合
$js = '{"a":1,"b":2}';
var_dump(json_decode($js)); // stdClassオブジェクト
var_dump(json_decode($js, true)); // 連想配列
🏁 まとめ
json_encode()
は PHP → JSON文字列json_decode()
は JSON文字列 → PHPの値$associative
の有無で「配列 or オブジェクト」が変わる- 今回の出力結果は 正解! 試験でもその理解でOKです ✅