Home > Article > Backend Development > How to implement classification in php
php method to implement classification: first establish a test database; then insert test data; finally output classification through recursion, code such as "for ($i = 0; $i < count($arr); $i ) {if ($arr[$i][1] == $fid) {...}}".
Recommendation: "PHP Video Tutorial"
The operating environment of this tutorial: windows7 system, PHP5. Version 6, this method is suitable for all brands of computers.
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] . "
"; getCate($arr[$i][0]); //递归 } } }The above is the detailed content of How to implement classification in php. For more information, please follow other related articles on the PHP Chinese website!