zoukankan      html  css  js  c++  java
  • 无限级分类及生成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     }
  • 相关阅读:
    ajax 笔记
    EM Algorithm
    Support Vector Machine
    Factor Analysis
    Local weighted regression
    一点突发奇想
    纳什均衡
    自驾崇明东滩湿地
    程序员热力学第二定律
    SQL Server Identity 属性的问题
  • 原文地址:https://www.cnblogs.com/walblog/p/8005333.html
Copyright © 2011-2022 走看看