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;