Home  >  Article  >  Backend Development  >  How to implement classification in php

How to implement classification in php

藏色散人
藏色散人Original
2020-11-24 09:09:523252browse

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) {...}}".

How to implement classification in php

Recommendation: "PHP Video Tutorial"

The operating environment of this tutorial: windows7 system, PHP5. Version 6, this method is suitable for all brands of computers.

Realize unlimited classification

Step one: Establish a test database

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;

Step two: Insert test data

INSERT INTO `category` ( `fid`, `value`) VALUES
(1,'a'),
(1,'b'),
(2,'c'),
(2,'d'),
(4,'e')

Step three: Recursive output classification

  
    $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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn