zoukankan      html  css  js  c++  java
  • php 单表数据转化为json格式

    有上图结构数据表,用PHP如何生成下面结构的JSON?
    
    [
    
        {
    
            "name":"电脑",
    
            "id":"1",
    
            "list":[
    
                {
    
                    "name":"无法开机",
    
                    "id":"3"
    
                },
    
                {
    
                    "name":"无法联网",
    
                    "id":"4"
    
                },
    
                {
    
                    "name":"蓝屏",
    
                    "id":"5"
    
                }
    
            ]
    
        },
    
        {
    
            "name":"打印机",
    
            "id":"2",
    
            "list":[
    
                {
    
                    "name":"卡纸",
    
                    "id":"6"
    
                },
    
                {
    
                    "name":"加粉",
    
                    "id":"7"
    
                }
    
            ]
    
        }
    
    ]
    
    
    $sql="select id,name,superior from table where 1=1";
    
    $requ = mysqli_query($con,$sql);
    
    $items = array();
    
    while($rs=mysqli_fetch_array($requ)){
    
    $a=array("title"=>$rs['name'],"value"=>$rs['id'],"pid"=>$rs['superior']);
    
    array_push($items,$a);
    
    }
    
    
     
    
    $generateTree = function ($items, $parentKey = 'pid') {
    
        $tree = $temp = array();
    
        foreach ($items as $item) {
    
            $temp[$item['value']] = $item;
    
        }
    
        foreach ($items as $item) {
    
            if (isset($temp[$item[$parentKey]])) {
    
                $temp[$item[$parentKey]]['list'][] = &$temp[$item['value']];
    
            } else {
    
                $tree[] = &$temp[$item['value']];
    
            }
    
            unset($temp[$item['value']][$parentKey]);
    
        }
    
        return $tree;
    
    };
    
    
     
    
    $data = json_encode($generateTree($items));
    
    echo $data;
  • 相关阅读:
    Android 禁用以及捕捉home键
    android中正确导入第三方jar包
    使用SharedPreferences进行数据存储
    tomcat不安全因素
    spring边边角角
    宏定义
    C++变量对比java变量所占内存
    结构指针的分析
    对结构使用指针
    什么是程序文件?
  • 原文地址:https://www.cnblogs.com/kevin-yang123/p/14153998.html
Copyright © 2011-2022 走看看