Home >Backend Development >PHP Tutorial >Solution to generate nested JSON in PHP_PHP tutorial
PHP generates nested JSON
({
"aa": [
{
"Id": "0",
"title": "title",
},
{
"Id": "1",
"title": "title",
}
],
"bb":[
{
…
},
{
....
}
]
})
How does PHP generate 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){
// Recursively perform urlencode operation on each element in the array to protect Chinese characters
array_walk_recursive($data, 'jsonFormatProtect');
// json encode
$data = json_encode($data);
// urldecode the urlencode content
$data = urldecode($data);
// Indentation 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;
}
/**Urlencode array elements
* @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' => 'Title'
), array( 'Id' => 1, 'title' => 'title' ), ), 'bb' => array( 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" } ]}