2022-02-21 04:21:27
PHP 提供了内置函数 json_decode() 来将 JSON 格式的字符串转换为 PHP 可操作的数据结构(对象或数组)。掌握其使用方法对于高效处理 JSON 数据至关重要。
json_decode() 的基本语法如下:
mixed json_decode ( string $json , bool $associative = false , int $depth = 512 , int $options = 0 )当 $associative 为 false 或省略时,JSON 被解码为 stdClass 对象,使用 -> 访问属性。
示例:
$json_string = '{"WEAPON_PISTOL":{"ammo":227}}';$obj = json_decode($json_string);echo $obj->WEAPON_PISTOL->ammo; // 输出: 227模式 2:解析为关联数组设置 $associative = true 时,JSON 对象转为关联数组,使用 [] 访问键。
示例:
$json_string = '{"WEAPON_PISTOL":{"ammo":227}}';$arr = json_decode($json_string, true);echo $arr['WEAPON_PISTOL']['ammo']; // 输出: 227选择建议:
输出:
WEAPON_PISTOL has 227 rounds.WEAPON_GUN has 6 rounds.WEAPON_RIFLE has 90 rounds.关联数组模式遍历$weapons_arr = json_decode($json_string, true);foreach ($weapons_arr as $weaponName => $weaponData) { echo "$weaponName has {$weaponData['ammo']} rounds.n";}输出与对象模式相同,仅访问方式不同。
外部用单引号包裹含双引号的 JSON:$json = '{"key":"value with "quotes""}';
或转义内部双引号:$json = "{"key":"value with "quotes""}";
当 JSON 格式错误时,json_decode() 返回 null,需用以下方裂缓式检测:
$invalid_json = '{"name":"John", "age":30,}'; // 尾部逗号错误$data = json_decode($invalid_json);if ($data === null && json_last_error() !== JSON_ERROR_NONE) { echo "错误: " . json_last_error_msg();}3. 访问方式混淆错误json_decode() 的灵活性体现在:
通过合理选择解析模式、严格检查错误、注意访问方式规范,可以高效安全地处理各种 JSON 数据场景。对于现代 Web 开发中频繁的 API 数据交互,掌握这些技巧尤为重要。