gpt4 book ai didi

php - 从 MySQL 数据库中列出类别然后在 PHP 中列出子类别

转载 作者:行者123 更新时间:2023-11-29 02:01:53 24 4
gpt4 key购买 nike

我一直致力于构建一个简单的电子商务系统的项目,在我开始显示类别导航之前一直运行良好。

当我在 MySQL 中构建类别时,我有类似的东西:

id             name             parent_id
1 books null
2 art 1
3 biography 1
4 games null
5 electronics null
6 FPS 4

我编写了以下 SQL 来检索父类别,然后检索子类别:

SELECT parent.name AS parent_name, child1.name AS child1_name
FROM categories AS parent
LEFT OUTER JOIN categories AS child1 ON child1.parent_id = parent.id
WHERE parent.parent_id IS NULL
ORDER BY parent_name, child1_name

结果是一个包含多个数组的数组:

Array
(
[0] => Array
(
[parent_name] => Books
[child1_name] => Art
)

[1] => Array
(
[parent_name] => Books
[child1_name] => Biography
)

[2] => Array
(
[parent_name] => Clothes, Shoes & Watches
[child1_name] =>
)

[3] => Array
(
[parent_name] => Computers & Office
[child1_name] =>
)

[4] => Array
(
[parent_name] => Electronics
[child1_name] =>
)
)

我无法将此信息显示为无序列表。期望的效果是这样的:

<ul>
<li>Books
<ul>
<li>Art</li>
<li>Biography</li>
</ul>
</li>
<li>Computers</li>
<li>Electronics</li>
</ul>

有没有人能解决这个问题?我是否需要更改我的 MySQL 代码甚至数据库结构?

提前致谢。

最佳答案

解决方案并不简单,但可以为您工作:)。

$newArray = array();
foreach($arrayFromDatabase as $key => $category){
//replace key
$newArray[$category['parent_name']][] = $category['child1_name'];
}

//Open list
$toEcho = "<ul>";
foreach($newArray as $name => $subCat){
if(!empty($subCat)){
$toEcho_ = "<ul>";
foreach($subCat as $cat){
$toEcho_ .= "<li>$cat</li>";
}
$toEcho_ .= "</ul>";
$toEcho .= "<li>$name $toEcho_</li>";
} else{
$toEcho .= "<li>$name</li>";
}
}

//Close list
echo $toEcho . "</ul>";

关于php - 从 MySQL 数据库中列出类别然后在 PHP 中列出子类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13442243/

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