无限级分类及生成json数据

第一步,先去数据库查询类别数据,然后交给生成json数据的函数处理,代码如下:

1 /*生成类别JSON数据*/
2     public function wirteJson(){
3         $dataInfo = 	hinkDb::query("select id as v,name as n,pid from think_pro_category");
4         $data = $this->getCategoryJson($dataInfo);
5         return $data;
6     }

第二步,将查询出来的类别数据重新归类排序,代码如下:

 1 /**
 2  *处理分类数组
 3 **/
 4 function generateTree($items) {
 5     $tree = array();
 6     foreach($items as $item){
 7         if(isset($items[$item['pid']])){
 8             $items[$item['pid']]['s'][] = &$items[$item['v']];
 9         }else{
10             $tree[] = &$items[$item['v']];
11         }
12     }
13     return $tree;
14 }

第三步,生成json数据,并返回数据,代码如下:

 1 /**
 2      * 功能:无限级类别json数据生成
 3      * 参数:$data 类别查询结果集
 4      * 返回值:$json 递归查询排序后的json数据
 5      */
 6     public function getCategoryJson($dataInfo) {
 7         /*生成json数据*/
 8         foreach($dataInfo as $category) {
 9             $tree[$category['v']] = $category;
10             $tree[$category['v']]['s'] = array();
11         }
12         $content = json_encode(generateTree($tree));
13         $content = str_replace(',"s":[]', "", $content);
14         // for( $i = 0; $i < count($dataInfo); $i++ ) {
15         //     $content = str_replace('"'.$dataInfo[$i]['v'].'":', "", $content);
16         // }
17         //$content = '['.substr($content,1,strlen($content)-2).']';
18         //return $content;
19         /*写入文件*/
20         //文件存放路径
21         $filePath = $_SERVER['DOCUMENT_ROOT'].DS.'/category/category.json';
22         $returnval = file_put_contents($filePath,$content);
23         // $fopen = fopen($filePath,'w+');
24         // fwrite($fopen,$content);
25         // fclose($fopen);
26         return $returnval;
27     }
原文地址:https://www.cnblogs.com/walblog/p/8005333.html