【发布时间】:2017-06-16 08:24:36
【问题描述】:
我正在尝试修改一些代码,这些代码为数据库中的菜单创建对象数组和对象数组,我需要它来将 SubCategoryID 添加到数组中的每个项目
对于我的一生,我对如何做到这一点感到精神空白
<?php
include_once ('includes/sqlopen.php');
$sql = mysqli_query($conn, "SELECT CategoryName, SubcategoryName,
SubcategoryID
FROM products
GROUP BY SubcategoryID
ORDER BY CategoryName");
$menu = array();
while ($row = mysqli_fetch_assoc($sql)) {
if (!in_array($row['CategoryName'], $menu['category'])) {
$menu['category'][] = $row['CategoryName'];
}
if (!empty($row['SubcategoryName']))
$menu['SubcategoryName'][$row['CategoryName']][] = $row['SubcategoryName'];
}
echo "Start of Array";
echo "<br>";
foreach ($menu['category'] as $cat) {
echo $cat."<br>";
foreach ($menu['SubcategoryName'][$cat] as $subcat) {
echo "--" . $subcat."<br>";
}
}
echo "<br>";
echo "End of Array";
include_once ('includes/sqlclose.php');
?>
基本上我想实现这个:
Parent Cat 1 (link to prodlist.php?id=100)
--Child Cat1 (link to prodlist.php?id=103)
--Child Cat2 (link to prodlist.php?id=104)
Parent Cat 2 (link to prodlist.php?id=200)
Parent Cat 3 (link to prodlist.php?id=300)
--Child Cat1 (link to prodlist.php?id=301)
--Child Cat2 (link to prodlist.php?id=302)
数据库布局:
CategoryName SubcategoryName ItemName SubCategoryID
ParentCat1, ChildCat1, Item1, 103
ParentCat1, ChildCat1, Item2, 103
ParentCat1, ChildCat2, Item1, 104
ParentCat2, Item1, 200
ParentCat3, ChildCat1, Item1, 301
ParentCat3, ChildCat2, Item2, 302
** 更新 - 感谢所有试图帮助我的人,我知道我可能不太擅长解释我需要帮助的内容..
我已经玩了一段时间了,它正在做我想做的事。我只是有一个小故障,如果 2 个不同的父类别具有相同名称的子类别,它会将两个子类别 ID 添加到数组中
$menu = array();
while ($row = mysqli_fetch_assoc($sql)) {
if (!in_array($row['CategoryName'], $menu['category'])) {
$menu['category'][] = $row['CategoryName'];
}
if (!empty($row['SubcategoryName']))
$menu['SubcategoryName'][$row['CategoryName']][] = $row['SubcategoryName'];
$menu['SubcategoryID'][$row['SubcategoryName']][] = $row['SubcategoryID'];
}
输出
--Accessories
id--766
id--243
id--992
id--871
id--977
Monitor Arms
--Spacedec
id--789
--Visidec
id--791
--Telehook
id--792
--Spacepole
id--804
--Accessory
id--866
--Monitor Accessories
id--990
id--584
--Stands
id--991
id--538
【问题讨论】:
-
如果您告诉我们问题出在哪里,我们可以花更少的时间自己解决问题
-
对于从数据库添加到数组的每个项目,我希望它添加 SubCategoryID 以便在打开菜单项时将其作为变量传递到下一页\跨度>
-
您能否将 ParentCatid 添加到您的选择中并更新您的“数据库已铺设”部分。
-
添加了更新.. 感谢大家的帮助.. 我知道当我需要帮助时我不擅长解释事情