luinstein 发表于 2012-10-23 15:32:58

用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']['p'];
                }else{
                        $new_r[$i]['key']=$k;
                        $new_r[$i]['data_type'] = gettype($v);
                }
                $i++;
      }
      return $new_r;
}
页: [1]
查看完整版本: 用php对json数据进行解析,获取各字段格式