我有以下代码:
$catsQuery = "
SELECT id, category
FROM categories
ORDER BY category
";
$catsSql = mysqli_query($link, $catsQuery);
$cats = array();
mysqli_data_seek($catsSql, 0);
while($rowCats = mysqli_fetch_assoc($catsSql))
{
$cats[$rowCats['id']]['catName'] = $rowCats['category'];
}
foreach ($cats as $catKey => $cat['$catName'])
{
$pageContent .= "<p>$catKey | $catName</p>
";
}
这两列id
包含category
如下数据:
- 编号 | 类别
- 1 | 鞋
- 2 | 衬衫
- 3 | 帽子
我想做的是将表中的所有行categories
变成一个名为的局部变量cats
在 while 循环中,当每个 rows 数组键成为类别 id 时,会生成一个本地数组,然后将类别名称分配给该键。var_dump($cats)
表明每一行都被添加到变量中,正如我所描述的。
但是在 foreach 中,由于某种原因,它作为新行返回的每个 id,但类别的名称显示为最后可能的类别名称,跨越所有键。
为什么变量上的转储显示一组数据,但以这种内容方式打印的循环显示这个奇怪的打嗝?
像这样:
- 1 | 帽子
- 2 | 帽子
- 3 | 帽子
如果有人可以阐明我做错了什么导致此问题,将不胜感激。
谢谢你!!
编辑:
由于以下答案而创建的功能代码:
//categories to local array
$catsQuery = "
SELECT id, category, catDirPath
FROM categories
ORDER BY category
";
$catsSql = mysqli_query($link, $catsQuery);
$cats = array();
mysqli_data_seek($catsSql, 0);
while($rowCats = mysqli_fetch_assoc($catsSql))
{
$cats[$rowCats['id']]['catName'] = $rowCats['category'];
$cats[$rowCats['id']]['catPath'] = $rowCats['catDirPath'];
}
// subCats to local array
$subsQuery = "
SELECT id, subCat, category_id, subDirPath
FROM subCats, sub_categories
WHERE subCats.id = sub_categories.sub_id
ORDER BY category_id
";
$subsSql = mysqli_query($link, $subsQuery);
$subs = array();
mysqli_data_seek($subsSql, 0);
while($rowSubs = mysqli_fetch_assoc($subsSql))
{
$subs[$rowSubs['id']]['subName'] = $rowSubs['subCat'];
$subs[$rowSubs['id']]['catId'] = $rowSubs['category_id'];
$subs[$rowSubs['id']]['subPath'] = $rowSubs['subDirPath'];
}
// loop through categories and if subs exist, add to resultset and display
foreach ($cats as $catId => $cat)
{
$pageContent .= "
<div style='margin-bottom: 10px; border black solid 1px;'>
<ul>
<li style='list-style-type: none; margin-bottom: 5px;'><a href='$docPath/category/{$cat['catPath']}/'>{$cat['catName']}</a></li>
";
foreach ($subs as $subId => $sub)
{
if($sub['catId'] == $catId)
{
$pageContent .= "
<li style='list-style-type: circle; padding-left: 15px; font-size: 70%;'><a href='$docPath/category/{$cat['catPath']}/{$sub['subPath']}/'>{$sub['subName']}</a></li>
";
}
}
$pageContent .= "
</ul>
</div>
";
}