({
"aa": [
{
"Id": "0",
立即学习“PHP免费学习笔记(深入)”;
"title": "标题",
},
{
"Id": "1",
"title": "标题",
}
],
"bb":[
{
...
},
{
....
}
]
})
PHP如何生成这种嵌套的JSON
------解决方案--------------------
/** Json数据格式化
* @param Mixed $data 数据
* @param String $indent 缩进字符,默认4个空格
* @return JSON
*/
function jsonFormat($data, $indent=null){
// 对数组中每个元素递归进行urlencode操作,保护中文字符
array_walk_recursive($data, 'jsonFormatProtect');
// json encode
$data = json_encode($data);
// 将urlencode的内容进行urldecode
$data = urldecode($data);
// 缩进处理
$ret = '';
$pos = 0;
$length = strlen($data);
$indent = isset($indent)? $indent : ' ';
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
$newline = " ";
$prevchar = '';
$outofquotes = true;
for($i=0; $i
$char = substr($data, $i, 1);
if($char=='"' && $prevchar!='\'){
$outofquotes = !$outofquotes;
}elseif(($char=='}' ------解决方案-------------------- $char==']') && $outofquotes){
$ret .= $newline;
$pos --;
for($j=0; $j
$ret .= $indent;
}
}
$ret .= $char;
if(($char==',' ------解决方案-------------------- $char=='{' ------解决方案-------------------- $char=='[') && $outofquotes){
$ret .= $newline;
if($char=='{' ------解决方案-------------------- $char=='['){
$pos ++;
}
for($j=0; $j
$ret .= $indent;
}
}
$prevchar = $char;
}
return $ret;
}
/** 将数组元素进行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' => '标题'
), array( 'Id' => 1, 'title' => '标题' ), ), 'bb' => array( array( 'Id' => 2, 'title' => '标题' ), array( 'Id' => 3, 'title' => '标题' ), ));echo jsonFormat($arr);{ "aa":[ { "Id":"0", "title":"标题" }, { "Id":"1", "title":"标题" } ], "bb":[ { "Id":"2", "title":"标题" }, { "Id":"3", "title":"标题" } ]}
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号