gpt4 book ai didi

php - 从sql数据库的类别列表中订购一组子类别

转载 作者:搜寻专家 更新时间:2023-10-30 20:29:29 25 4
gpt4 key购买 nike

我有这个代码,但我不知道如何订购我的查询

function get_All_Categories(){
//new instance of mysqli
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
//if it doesn't work give an error
if (!$mysqli) {
die('There was a problem connecting to the database.');
}
$queryCats ="SELECT Catid, Catname
FROM ProductCats
ORDER BY Catid";
$querySubCats ="SELECT Subcatname, Parentid
FROM ProductSubCats, ProductCats
WHERE ProductSubCats.Parentid = ProductCats.Catid
ORDER BY Subcatname;";
if ($catResults = $mysqli->query($queryCats)){
if (!$catResults) {
echo 'Could not run query: ' . mysql_error();
exit;
}
else{
$subCatResults = $mysqli->query($querySubCats);
}
while ($rows = $catResults->fetch_assoc()) {
echo '<div class = "categoryCluster">';
echo '<a href="../index.php?Cat='.$rows["Catname"].'">'.$rows["Catname"].'</a>';
echo '<br>';
while($rowsSub = $subCatResults->fetch_assoc()){
echo '<div class="subCategoryCluster">';
echo '&emsp;'.'<a href="../index.php?Cat='.$rows["Catname"].'&'.'Subcat='.$rowsSub["Subcatname"].'">'.$rowsSub["Subcatname"].'</a>';
echo '<br>';
echo '</div>';
}
echo '</div>';
}
}
$mysqli->close();
}

显示此输出:

Header 1
 Subcat 1
 Subcat 2
 OtherSubcat 1
Header 2
Header 3
Header 4
Header 5
Header 6

但我的问题是subcat 1和subcat 2的parentid为1,符合header 1,而othersubcat 1的parentid为5。实际上符合header 5。是的,在我的循环中,它紧接着其他 2 个显示。

现在我知道为什么这是错误的了,这是因为 while 循环中的 while 循环命令它最后出现,并把它粘在那里。

但我完全不知道如何修改它以便显示:

Header 1
 Subcat 1
 Subcat 2
Header 2
Header 3
Header 4
Header 5
 OtherSubcat 1
Header 6

示例表:

>     ProductSubCats
> Subcatid | Subcatname | Parentid
> 1 | Subcat 1 | 1
> 2 | Subcat 2 | 1
> 3 | Othersubcat 3 | 5
>
>
>
> ProductCats
> Cat id | Catname
> 1 | Header 1
> 2 | Header 2
> 3 | Header 3
> 4 | Header 4
> 5 | Header 5
> 6 | Header 6

谢谢你的帮助

最佳答案

按照@Pasha Bitz 所说的,对于您正在尝试做的事情。

尝试以下操作:

$categories = array();
$sub_categories = array();
while ($rows = $catResults->fetch_assoc()) {
$categories[$rows['Catid']] = $rows['Catname'];
}
while($rows = $subCatResults->fetch_assoc()){
if (!isset($sub_categories[$rows['Parentid']])) {
$sub_categories[$rows['Parentid']] = array();
}
$sub_categories[$rows['Parentid']][] = $rows['Subcatname'];
}
foreach ($categories as $cat_id => $name) {
echo '<div class = "categoryCluster">';
echo '<a href="../index.php?Cat='.$name.'">'.$name.'</a>';
echo '<br>';
if (isset($sub_categories[$cat_id])) {
foreach($sub_categories[$cat_id] as $cat_id => $sub_cat_name) {
echo '<div class="subCategoryCluster">';
echo '&emsp;'.'<a href="../index.php?Cat='.$name.'&'.'Subcat='.$sub_cat_name.'">'.$sub_cat_name.'</a>';
echo '<br>';
}
}
}

这应该可以为您解决这个问题,研究代码以便您了解这里发生了什么。

关于php - 从sql数据库的类别列表中订购一组子类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14076693/

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