gpt4 book ai didi

php - 如何计算父类别及其后代中的项目?

转载 作者:行者123 更新时间:2023-11-30 22:24:41 25 4
gpt4 key购买 nike

我有两个表:类别和对象。类别可以有一个或多个 child 。这些 child 可以有自己的 child 。所以,层次是无限的。一个 child 只能有一个 parent 。父类别是parent_id 为NULL 的类别。类别有对象(一对多关系)。

示例数据:

分类表

id   name       parent_id    
1 Sports NULL
2 Home NULL
3 Fashion NULL
4 Cycling 1
5 Football 1
6 Bath 2
7 Bedroom 2
8 Lighting 7

假设类别中的对象数量如下所示:

name       COUNT(object)   
Sports 5
Home 3
Fashion 4
Cycling 2
Football 3
Bath 2
Bedroom 1
Lighting 3

我只需要使用纯 MySql 或 MySql 和 PHP 获取父类别的对象计数,包括其后代中的对象计数。

这是我正在寻找的结果。

Sports     5 + 2(for Cycling)+3(for Football) = 10
Home 3+2(Bath)+1(Bedroom)+3(Lighting)= 9
Fashion 4

我知道嵌套集,但无法更改当前的数据库结构。

最佳答案

下面的 php 代码可以解决这个问题,也许有更好的答案,但我现在已经告诉了你

<?php
try{
$conn = new PDO('mysql:host=localhost;dbname=test', 'root', 'root');
$stm = $conn->prepare('select tem.id, tem.num, c.name, c.parent_id from category c inner join (SELECT c.id ,count(c.id) as num FROM `category` c left join object o on o.category = c.id
group by c.id) tem on c.id = tem.id');
$stm->execute();
$result = $stm->fetchAll(PDO::FETCH_OBJ);
$temp = array();
foreach($result as $row){
$temp[$row->id] = $row;
}


$pre_final = moh($temp);
$final = array();
foreach ($pre_final as $row){
if(!$row->parent_id){
$final[] = $row;
}
}

print_r($final);
}
catch(PDOException $e){
print "Error!: " . $e->getMessage() . "<br/>";
die();
}

function moh($arr){
$flag = true;
foreach($arr as $row){
if(!$row->parent_id){

} else{
$arr[$row->parent_id]->num += $row->num;
$row->num = 0;
}
}



foreach($arr as $row){
if(!$row->parent_id){

} else{
if($row->num != 0){
$flag = false;
break;
}
}
}

if($flag){
return $arr;
} else{
return moh($arr);
}


}

关于php - 如何计算父类别及其后代中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35607851/

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