您好,欢迎访问一九零五行业门户网

PHP生成嵌套JSON解决思路_PHP教程

php生成嵌套json
({
aa: [
{
id: 0,
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 : ' ';
$newline = \n;
$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:标题 } ]}
http://www.bkjia.com/phpjc/820425.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/820425.htmltecharticlephp生成嵌套json ({ aa: [ { id: 0, title: 标题, }, { id: 1, title: 标题, } ], bb:[ { ... }, { .... } ] }) php如何生成这种嵌套的json ------解决方案--------------...
其它类似信息

推荐信息