PHP数组转JSON字符串

Guanhui
发布: 2023-03-01 11:42:01
原创
3843 人浏览过

PHP数组转JSON字符串

PHP数组转JSON字符串

在PHP中可以使用“json_encode()”函数将数组转为字符串,该函数用于把数组进行JSON编码,其语法是“json_encode(array)”,其参数array表示要转换数组,成功则返回JSON编码的字符串。

示例

<?php
$a = array(&#39;<foo>&#39;,"&#39;bar&#39;",&#39;"baz"&#39;,&#39;&blong&&#39;, "\xc3\xa9");

echo "Normal: ",  json_encode($a), "\n";
echo "Tags: ",    json_encode($a, JSON_HEX_TAG), "\n";
echo "Apos: ",    json_encode($a, JSON_HEX_APOS), "\n";
echo "Quot: ",    json_encode($a, JSON_HEX_QUOT), "\n";
echo "Amp: ",     json_encode($a, JSON_HEX_AMP), "\n";
echo "Unicode: ", json_encode($a, JSON_UNESCAPED_UNICODE), "\n";
echo "All: ",     json_encode($a, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE), "\n\n";

$b = array();

echo "Empty array output as array: ", json_encode($b), "\n";
echo "Empty array output as object: ", json_encode($b, JSON_FORCE_OBJECT), "\n\n";

$c = array(array(1,2,3));

echo "Non-associative array output as array: ", json_encode($c), "\n";
echo "Non-associative array output as object: ", json_encode($c, JSON_FORCE_OBJECT), "\n\n";

$d = array(&#39;foo&#39; => &#39;bar&#39;, &#39;baz&#39; => &#39;long&#39;);

echo "Associative array always output as object: ", json_encode($d), "\n";
echo "Associative array always output as object: ", json_encode($d, JSON_FORCE_OBJECT), "\n\n";
?>
登录后复制

输出结果

Normal: ["<foo>","&#39;bar&#39;","\"baz\"","&blong&","\u00e9"]
Tags: ["\u003Cfoo\u003E","&#39;bar&#39;","\"baz\"","&blong&","\u00e9"]
Apos: ["<foo>","\u0027bar\u0027","\"baz\"","&blong&","\u00e9"]
Quot: ["<foo>","&#39;bar&#39;","\u0022baz\u0022","&blong&","\u00e9"]
Amp: ["<foo>","&#39;bar&#39;","\"baz\"","\u0026blong\u0026","\u00e9"]
Unicode: ["<foo>","&#39;bar&#39;","\"baz\"","&blong&","é"]
All: ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\u0026blong\u0026","é"]

Empty array output as array: []
Empty array output as object: {}

Non-associative array output as array: [[1,2,3]]
Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}}

Associative array always output as object: {"foo":"bar","baz":"long"}
Associative array always output as object: {"foo":"bar","baz":"long"}
登录后复制

推荐教程:《PHP

以上是PHP数组转JSON字符串的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
php
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板