PHP如何将数组转换成JSON?

PHP如何将数组转换成JSON?

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:域名与空间、虚拟空间、营销软件、网站建设、公安网站维护、网站推广。

在PHP中可以通过使用函数“json_encode()”将数组转为JSON,该函数的作用是对变量进行JSON编码,函数语法为“json_encode($val)”,返回值为JSON编码的字符串。

使用示例

<?php
$a = array('<foo>',"'bar'",'"baz"','&blong&', "\\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('foo' => 'bar', 'baz' => 'long');

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>","'bar'","\\"baz\\"","&blong&","\\u00e9"]
Tags: ["\\u003Cfoo\\u003E","'bar'","\\"baz\\"","&blong&","\\u00e9"]
Apos: ["<foo>","\\u0027bar\\u0027","\\"baz\\"","&blong&","\\u00e9"]
Quot: ["<foo>","'bar'","\\u0022baz\\u0022","&blong&","\\u00e9"]
Amp: ["<foo>","'bar'","\\"baz\\"","\\u0026blong\\u0026","\\u00e9"]
Unicode: ["<foo>","'bar'","\\"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?
分享链接:https://www.cdcxhl.com/article0/cgssoo.html

成都网站建设公司_创新互联,为您提供网站策划自适应网站商城网站ChatGPT网站维护网站排名

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都seo排名网站优化