创星网络[分享知识 传递快乐]
标题:
用php对json数据进行解析,获取各字段格式
[打印本页]
作者:
luinstein
时间:
2012-10-23 15:32
标题:
用php对json数据进行解析,获取各字段格式
自己写的一段代码。
<?php
/**
* by luinstein@cxweb.com.cn 2012-05-30 对json数据进行解析,获取各字段格式,适用于接口文档的数据类型显示
*/
$json = "
{
\"count\": 1,
\"list\": [
{
\"id\": 1,
\"title\": \"t\",
\"photos\": [
{
\"url\": \"http://www.cxweb.com.cn/static/image/common/logo.png\"
},
{
\"url\": \"http://www.cxweb.com.cn/data/attachment/common/9f/common_56_icon.jpg\"
}
]
},
{
\"id\": 2,
\"title\": \"t2\",
\"photos\": []
}
]
}
";
$res = json_decode($json,true);
$new_r = getFiled($res);
$new_r = clearP($new_r);
print_r($new_r);
function clearP($new_r){
foreach ($new_r as $k=>$v){
unset($new_r[$k]['p']);
if($new_r[$k]['p_new']){
$new_r[$k]['p_new'] = clearP($new_r[$k]['p_new']);
}
}
return $new_r;
}
function getFiled($res){
$new_r = array();
$i = 0;
foreach ($res as $k=>$v){
if(is_numeric($k)&&$k>0){
continue;
}
if(is_array($v)){
$new_r[$i]['key']=$k;
$new_r[$i]['data_type'] = gettype($v);
$new_r[$i]['p'] = getFiled($v);
$new_r[$i]['p_new'] = $new_r[$i]['p'][0]['p'];
}else{
$new_r[$i]['key']=$k;
$new_r[$i]['data_type'] = gettype($v);
}
$i++;
}
return $new_r;
}
复制代码
欢迎光临 创星网络[分享知识 传递快乐] (http://bbs.cxweb.com.cn/)
Powered by Discuz! X3