gpt4 book ai didi

php - 使用嵌套集模型的 SQL 查询和 PHP 操作

转载 作者:行者123 更新时间:2023-11-29 05:37:54 25 4
gpt4 key购买 nike

我正在阅读这篇文章,http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ .

我想举一个简单的例子,然后问你如何得到想要的结果?所以这里是示例:

+---------+-----------------------------+
| product_id | product_name |
+---------+-----------------------------+
| 1 | Example Product |
+---------+-----------------------------+
+---------+-----------------------------+
| product_id | category_id |
+---------+-----------------------------+
| 1 | 2 |
| 1 | 4 |
+---------+-----------------------------+
+-------------+--------------------+------+------+
| category_id | name | lft | rgt |
+-------------+--------------------+------+------+
| 1 | Electronics | 1 | 8 |
| 2 | Televisions | 2 | 3 |
| 3 | Portable Electronics | 4 | 7 |
| 4 | CD Players | 5 | 6 |
+-------------+--------------------+------+------+

我希望能够在查询然后在 PHP 中操作数据后以 HTML 显示以下结果:

"Example Product" Categories:
Electronics
Televisions
Portable Electronics
CD Players

你能帮助我完成 PHP 中的查询和操作以获得这个结果吗?

一些需要考虑的细节:

  1. 请注意这两个类别是如何在 Electronics 下的,但是“Electronics”在这里只出现一次,在下面显示它所属的每个子类别
  2. 结果最终应该是一个 PHP 多维数组,类别包含一个子类别数组,每个子类别包含一个子类别数组(如果存在)。

我认为打印深度对于在 HTML 中构建正确的树非常重要。

最佳答案

我认为这是一个很好的挑战..这是我的解决方案:

基本上:读取一个节点,然后 rgt 小于您的 rgt 的所有后续节点都是您的 child ,递归执行此操作。我使用 peek/consume 像往常一样从 mysql 中读取数据。

如果查询没有给出结果,或者如果数据集损坏,脚本将中断或循环。

class NestedNodeReader {

private $mysql_result;
private $peeked = false;
private $last_peek;

public function __construct($mysql_result) {
$this->mysql_result = $mysql_result;
}

public function getTree() {
$root = $this->consume();
$root["children"] = $this->getSubTree($root["rgt"]);
return $root;
}

private function getSubTree($stop_at) {
$nodes = array();
$node = $this->peek();
while ($node["rgt"] < $stop_at) {
$node = $this->consume();
$node["children"] = $this->getSubTree($node["rgt"]);
$nodes[] = $node;
$node = $this->peek();
if (false === $node) {
break;
}
}
return $nodes;
}

private function peek() {
if (false === $this->peeked) {
$this->peeked = true;
$this->last_peek = mysql_fetch_assoc($this->mysql_result);
}
return $this->last_peek;
}

private function consume() {
if (false === $this->peeked) {
return mysql_fetch_assoc($this->mysql_result);
} else {
$this->peeked = false;
return $this->last_peek;
}
}
}

$query = "SELECT node.name, node.lft, node.rgt
FROM nested_category AS node,
nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND parent.name = 'ELECTRONICS'
ORDER BY node.lft;"
$mysql_result = mysql_query($query);
$nnr = new NestedNodeReader($mysql_result);
print_r($nnr->getTree());

关于php - 使用嵌套集模型的 SQL 查询和 PHP 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9184598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com