php - 如何在 TreeView 中显示层次结构数据库?

标签 php mysql treeview hierarchical-data adjacency-list-model

由于某些原因需要在 2 个不同的 TreeView 中显示来自 mysql 数据库的数据。

例子

TreeView 1(使用列表标签):

<li>level1 (Root)
	<ul>
		<li>level2</li>
		<li>level2
			<ul>
				<li>level3</li>
				<li>level3
					<ul>
						<li>level4</li>
						<li>level4</li>
					</ul>
				</li>
			</ul>
		</li>
		<li>level2
			<ul>
				<li>level3</li>
				<li>level3
					<ul>
						<li>level4</li>
						<li>level4</li>
					</ul>
				</li>
			</ul>
		</li>
	</ul>
</li>

TreeView 2:

enter image description here

我目前正在处理这个 php 脚本:

<?php
$servername = "localhost";
$username = "root";
$password = "psswd_here";
$dbname = "db_here";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error)
{
    die("Connection failed: " . $conn->connect_error);
}

$data = array();
$index = array();
$sql2 = "SELECT * FROM categories ORDER BY name";
$result2 = $conn->query($sql2);

if ($result2->num_rows > 0)
{
        while ($row2 = $result2->fetch_assoc())
        {
                $id = $row2["id"];
                $parent_id = $row2["parent_id"] === NULL ? "NULL" : $row2["parent_id"];
                $data[$id] = $row2;
                $index[$parent_id][] = $id;
        }
}
else
{
    echo "0 results";
}

$conn->close();

function display_child_nodes($parent_id, $level)
{
    global $data, $index;
    $parent_id = $parent_id === NULL ? "NULL" : $parent_id;
    if (isset($index[$parent_id]))
        {
        foreach ($index[$parent_id] as $id)
                {
            echo str_repeat("-", $level) . $data[$id]["name"] . "<br>";
            display_child_nodes($id, $level + 1);
        }
    }
}

echo '<ul>';
display_child_nodes(NULL, 0);
echo '</ul>';
?>

输出:

Electronics
-Cameras and Photography
--Accessories
--Camcorders
--Digital Cameras
-Cell Phones and Accessories
--Accessories
--Cell Phones
--Smartphones
-Computers and Tablets
--Desktops
--Laptops
--Netbooks
--Tablets
---Android
---iPad
-TV and Audio
--Home Audio
--Speakers and Subwoofers
--Televisions
---CRT
---LCD
---LED
---Plasma

这是数据库模式..

-- phpMyAdmin SQL Dump
-- version 4.4.12
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Oct 21, 2015 at 09:16 AM
-- Server version: 5.6.25
-- PHP Version: 5.6.11

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `binary`
--

-- --------------------------------------------------------

--
-- Table structure for table `categories`
--

CREATE TABLE IF NOT EXISTS `categories` (
  `id` int(10) NOT NULL,
  `parent_id` int(10) DEFAULT NULL,
  `name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `categories`
--

INSERT INTO `categories` (`id`, `parent_id`, `name`) VALUES
(1, NULL, 'Electronics'),
(2, 1, 'Cameras and Photography'),
(3, 1, 'Computers and Tablets'),
(4, 1, 'Cell Phones and Accessories'),
(5, 1, 'TV and Audio'),
(6, 2, 'Digital Cameras'),
(7, 2, 'Camcorders'),
(8, 2, 'Accessories'),
(9, 3, 'Laptops'),
(10, 3, 'Desktops'),
(11, 3, 'Netbooks'),
(12, 3, 'Tablets'),
(13, 4, 'Cell Phones'),
(14, 4, 'Smartphones'),
(15, 4, 'Accessories'),
(16, 5, 'Televisions'),
(17, 5, 'Home Audio'),
(18, 5, 'Speakers and Subwoofers'),
(19, 16, 'CRT'),
(20, 16, 'LCD'),
(21, 16, 'LED'),
(22, 16, 'Plasma'),
(23, 12, 'Android'),
(24, 12, 'iPad');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `categories`
--
ALTER TABLE `categories`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `categories`
--
ALTER TABLE `categories`
  MODIFY `id` int(10) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=25;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

最佳答案

请参阅下面的代码-

你只需要在这里为你的确切设计放置css

$servername = "localhost";
$username = "root";
$password = "psswd_here";
$dbname = "db_here";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error)
{
    die("Connection failed: " . $conn->connect_error);
}

function getCategory($parent_id){
    global $conn;
    $sql2 = "SELECT * FROM categories WHERE parent_id='".$parent_id."' ORDER BY name";
    $result2 = $conn->query($sql2);

    if (mysqli_num_rows($result2) > 0)
    {
        echo "<ul>";
        while ($row2 = mysqli_fetch_object($result2))
        {
            echo "<li>".$row2->name."</li>";
            getCategory($row2->id);     
        }
        echo "</ul>";
    }
}


//Set Parent id
$parent_id = 0;
getCategory($parent_id);

注意:根类parent_id为0

关于php - 如何在 TreeView 中显示层次结构数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33253166/

相关文章:

php - 基本邮件功能(PHP)附加 "-f"参数问题

c# - WPF TreeView : Why does virtualizing break BringIntoView()?

mysql - SQLSTATE一般错误1005无法创建表 '#sql-3d63_ca5dc9'(errno : 150)

mysql - 在 MySQL 的选择查询中使用 CASE、WHEN、THEN、END

php - 从 mysql 制作 html 选项列表的最有效方法?

css - 在 Odoo10 中选中复选框时,复选框轮廓消失

python - tkinter:如何序列化 TreeView ?

php - 在 MongoDB 查询中或使用 PHP 查找键名列表

php - 获取mysql查询的上一个和下一个id值

php - 将数百万行从一个 mysql 表迁移到另一个作为 Laravel 5 中的副本