php json

45次阅读
没有评论

共计 732 个字符,预计需要花费 2 分钟才能阅读完成。

PHP 中的 json_decode 函数用于将 JSON 格式的字符串转换为 PHP 对象或关联数组。
基本语法:

mixed json_decode (string $json [, bool $assoc = FALSE [, int $depth = 512 [, int $options = 0]]] )

参数说明:

  • $json:要解码的 JSON 字符串。
  • $assoc:可选参数,当为 true 时,返回关联数组;当为 false 时,返回对象。默认为 false。
  • $depth:可选参数,指定最大解析深度。默认为 512。
  • $options:可选参数,指定解析选项。默认为 0。

示例代码:

$json_string = '{"name":"John","age":30,"city":"New York"}';
// 解码为对象
$object = json_decode($json_string);
echo $object->name; // 输出:John
echo $object->age; // 输出:30
echo $object->city; // 输出:New York
// 解码为关联数组
$array = json_decode($json_string, true);
echo $array['name']; // 输出:John
echo $array['age']; // 输出:30
echo $array['city']; // 输出:New York

注意:

  • 如果 JSON 字符串无法解析,json_decode 函数将返回 null。
  • 如果要处理的 JSON 字符串中包含中文字符,可以在函数调用前使用 json_decode($json_string, true, 512, JSON_UNESCAPED_UNICODE) 来解码,并保留中文字符的原始编码。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-13发表,共计732字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)