站长资讯网
最全最丰富的资讯网站

PHP数组转JSON字符串

PHP数组转JSON字符串

PHP数组转JSON字符串

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

示例

<?php $a = array('<foo>',"'bar'",'"baz"','&blong&', "xc3xa9");  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), "nn";  $b = array();  echo "Empty array output as array: ", json_encode($b), "n"; echo "Empty array output as object: ", json_encode($b, JSON_FORCE_OBJECT), "nn";  $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), "nn";  $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), "nn"; ?>

输出结果

Normal: ["<foo>","'bar'",""baz"","&blong&","u00e9"] Tags: ["u003Cfoou003E","'bar'",""baz"","&blong&","u00e9"] Apos: ["<foo>","u0027baru0027",""baz"","&blong&","u00e9"] Quot: ["<foo>","'bar'","u0022bazu0022","&blong&","u00e9"] Amp: ["<foo>","'bar'",""baz"","u0026blongu0026","u00e9"] Unicode: ["<foo>","'bar'",""baz"","&blong&","é"] All: ["u003Cfoou003E","u0027baru0027","u0022bazu0022","u0026blongu0026","é"]  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》

赞(0)
分享到: 更多 (0)
网站地图   沪ICP备18035694号-2    沪公网安备31011702889846号