We continue to use the previous section to create a simple database test and table class
Connect to the database table:
<?php header("content-type:text/html;charset=utf8"); $link = mysqli_connect('localhost','yourname','password','test'); mysqli_set_charset($link, "utf8"); if (!$link) { die("连接失败:".mysqli_connect_error()); } ?>
Define a custom function get_array, the idea is basically the same as the previous section
Set the parent class pid = 0, use SQL statements to query its subclasses, and place the queried subclasses in $result
Use a while loop to get the subclasses, Call the custom function get_array, pass the id of the subclass into the custom function,
then continue to query the next level, and finally output the array.
<?php header("content-type:text/html;charset=utf8"); $link = mysqli_connect('localhost','yourname','password','test'); mysqli_set_charset($link, "utf8"); if (!$link) { die("连接失败:".mysqli_connect_error()); } function get_array($id=0){ global $link; $sql = "select id,title from class where pid= $id"; $result = mysqli_query($link,$sql);;//查询子类 $arr = array(); if($result){//如果有子类 while($rows=mysqli_fetch_assoc($result)){ //循环记录集 $rows['list'] = get_array($rows['id']); //调用函数,传入参数,继续查询下级 $arr[] = $rows; //组合数组 } return $arr; } } $list = get_array(0); //调用函数 print_r($list); //输出数组 ?>