PHP generates nested JSON
({
"AA": [
{
"Id": "0",
"title": "Titles",
},
{
"Id": "1",
"title": "Titles",
}
],
"BB": [
{
...
},
{
....
}
]
})
How PHP generates this nested JSON
------Solution--------------------
/** JSON data format
* @param Mixed $data data
* @param String $indent indent characters, default 4 spaces
* @return JSON
*/
function Jsonformat ($data, $indent =null) {
Each element in the array is recursively urlencode to protect the Chinese character
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 array elements to 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 ' => ' titles '
), array (' ID ' => 1, ' title ' => ' caption '), ' BB ' => Array (array (' ID ' => 2, ' title ' => ' title '), Array ( ' Id ' => 3, ' title ' => ']); Echo Jsonformat ($arr); {"AA": [{"Id": "0", "title": "title"}, {"id": "1", "title": "title"}, "BB": [{"Id": "2", "title": "title"}, {"id": "3", "title": "title"}]}