json_decode() 函数的第二个参数 $associative 是一个布尔值,用于控制 JSON 对象在 PHP 中的解码方式。当将其设置为 true 时,JSON 对象将被解码为关联数组;当设置为 false 时,JSON 对象将被解码为 stdClass 对象。默认值为 false。
语法:
php
function json_decode ($json, $associative = false, $depth = 512, $flags = 0) {}
以下是 json_decode() 函数的两种解码方式的示例:
-
当
$associative设置为true时,JSON 对象将被解码为关联数组:php<?php $json = '{"name": "John", "age": 30, "city": "New York"}'; $decoded = json_decode($json, true); print_r($decoded); // 输出:Array ( [name] => John [age] => 30 [city] => New York ) ?> -
当
$associative设置为false时(默认值),JSON 对象将被解码为 stdClass 对象:php<?php $json = '{"name": "John", "age": 30, "city": "New York"}'; $decoded = json_decode($json); print_r($decoded); // 输出:stdClass Object ( [name] => John [age] => 30 [city] => New York ) ?>
在这两个示例中,我们使用 json_decode() 函数解码 JSON 字符串。
第一个示例中,我们将 $associative 参数设置为 true,以便将 JSON 对象解码为关联数组。
第二个示例中,我们将 $associative 参数设置为默认值 false,以便将 JSON 对象解码为 stdClass 对象。