「PHP」json_decode関数でJSONデータを連想配列にするサンプル

関数

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
json_decode ( string $json [, bool $assoc = false [,
    int $depth = 512 [, int $options = 0 ]]] )
json_decode ( string $json [, bool $assoc = false [,     int $depth = 512 [, int $options = 0 ]]] )
json_decode ( string $json [, bool $assoc = false [,
    int $depth = 512 [, int $options = 0 ]]] )

引数1にJSON文字列を指定します。
引数2をtrueにすると連想配列形式のオブジェクトを返します。
引数2をfalseにするとオブジェクトを返します。
JSON エンコードされた文字列を受け取り、それを PHP の変数に変換します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<body>
<?php
$city = '{"tokyo":"東京","oosaka":"大阪","yokohama":"横浜"}';
$res = json_decode($city,true);
print $res["oosaka"];
?>
</body>
</html>
<!DOCTYPE html> <html> <body> <?php $city = '{"tokyo":"東京","oosaka":"大阪","yokohama":"横浜"}'; $res = json_decode($city,true); print $res["oosaka"]; ?> </body> </html>
<!DOCTYPE html>
<html>
<body>

<?php

$city = '{"tokyo":"東京","oosaka":"大阪","yokohama":"横浜"}';

$res = json_decode($city,true);

print $res["oosaka"];

?>

</body>
</html>

実行結果
大阪

PHP

Posted by arkgame