实现无限分类
第一步:建立测试数据库
CREATE TABLE `category` (
`id` smallint(5) unsigned NOT NULL auto_increment,
`fid` smallint(5) unsigned NOT NULL default '0',
`value` varchar(50) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
第二步:插入测试数据
INSERT INTO `category` ( `fid`, `value`) VALUES
(1,'a'),
(1,'b'),
(2,'c'),
(2,'d'),
(4,'e')
第三步:递归输出分类
$conn = mysqli_connect("localhost", "root", "1234", 'tp51');
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
mysqli_set_charset($conn, "utf8");
$sql = "SELECT * FROM category";
$res = $conn->query($sql);
if ($res->num_rows > 0) {
while ($row = $res->fetch_assoc()) {
$arr[] = array($row["id"],$row["fid"],$row["value"]);
}
} else {
echo "0 结果";
}
mysqli_close($conn);
getCate(1);
function getCate($fid = 0)
{
global $arr;
for ($i = 0; $i < count($arr); $i++) {
if ($arr[$i][1] == $fid) {
echo $arr[$i][2] . "<br>";
getCate($arr[$i][0]); //递归
}
}
}