PHP generates nested JSON
({
"AA": [
{
"Id": "0",
"title": "caption",
},
{
"Id": "1",
"title": "caption",
}
],
"BB": [
{
...
},
{
....
}
]
})
How PHP generates this nested JSON
------Solution--------------------
/** JSON data formatting
* @param Mixed $data data
* @param String $indent indent character, default 4 spaces
* @return JSON
*/
function Jsonformat ($data, $indent =null) {
UrlEncode each element recursively in an array, protecting Chinese characters
Array_walk_recursive ($data, ' jsonformatprotect ');
JSON encode
$data = Json_encode ($data);
UrlDecode the contents of the UrlEncode
$data = UrlDecode ($data);
Indent processing
$ret = ";
$pos = 0;
$length = strlen ($data);
$indent = Isset ($indent)? $indent: ";
$newline = "\ n";
$prevchar = ";
$outofquotes = true;
for ($i =0; $i <= $length; $i + +) {
$char = substr ($data, $i, 1);
if ($char = = ' "' && $prevchar! = ' \ \ ') {
$outofquotes =! $outofquotes;
}elseif (($char = = '} '------solution--------------------$char = = '] ') && $outofquotes) {
$ret. = $newline;
$pos--;
for ($j =0; $j < $pos; $j + +) {
$ret. = $indent;
}
}
$ret. = $char;
if ($char = = ', '------solution--------------------$char = = ' {'------solution--------------------$char = = ' [') && $ Outofquotes) {
$ret. = $newline;
if ($char = = ' {'------solution--------------------$char = = ' [') {
$pos + +;
}
for ($j =0; $j < $pos; $j + +) {
$ret. = $indent;
}
}
$prevchar = $char;
}
return $ret;
}
/** the elements of an array UrlEncode
* @param String $val
*/
Function Jsonformatprotect (& $val) {
if ($val!==true && $val!==false && $val!==null) {
$val = UrlEncode ($val);
}
}
Header (' Content-type:application/json;charset=utf8 ');
$arr = Array (
' AA ' = = Array (
Array
' Id ' = 0,
' Title ' = ' headline '
), array (' id ' = = 1, ' title ' + ' caption '), ' bb ' = = Array (' id ' = ' = ' + 2, ' title ' = ' title '), Array (' ID ' = 3, ' title ' = ' title '),); Echo Jsonformat ($arr); {"AA": [{"id": "0", "title": "title"}, {"id": "1", "title": "title"}], "BB": [{"id": "2", "title": "title"}, {"id": "3", "title": "title"}]}
http://www.bkjia.com/PHPjc/820425.html www.bkjia.com true http://www.bkjia.com/PHPjc/820425.html techarticle PHP generates nested JSON {AA: [{id:0, Title: Caption,}, {id:1, title: Title,}], bb:[{...}, {...}}) How does PHP generate this nested JSON------solution--------------...