PHP开发分类技术之使用递归实现无限级分类(二)

我们继续使用上一节创建一个简单的数据库test和表class

连接数据库表:

<?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());
}
?>

定义一个自定义函数get_array,思路与上一节思路基本相当

设置父类pid = 0, 使用SQL语句查询出它的子类,把查询出来的子类放置到$result中

使用while循环出子类,调用自定义函数get_array,将子类的id传入自定义函数中,

然后继续查询下一级,最后输出数组。

<?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); //输出数组
?>


继续学习
||
<?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); //输出数组 ?>
提交重置代码