page contents

PHP将两级联动数据表生成JSON数据

Pack 发布于 2020-03-12 11:05
阅读 1804
收藏 0
分类:PHP开发

有上图结构数据表,用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"

            }

        ]

    }

]


最佳答案 2020-03-24 17:11

535
Pack
Pack

$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;

请先 登录 后评论