Php 带乘积计数的递归菜单
我想创建一个包含产品总数的递归菜单,但是我现在被卡住了,因为我已经渲染了Topmenu,但是我找不到其他方法来实现它 我不想使用大量的MySQL查询,因为它会使我的网站非常慢 我正在使用的代码:Php 带乘积计数的递归菜单,php,recursion,menu,count,product,Php,Recursion,Menu,Count,Product,我想创建一个包含产品总数的递归菜单,但是我现在被卡住了,因为我已经渲染了Topmenu,但是我找不到其他方法来实现它 我不想使用大量的MySQL查询,因为它会使我的网站非常慢 我正在使用的代码: require 'db.php'; $result = mysql_query("SELECT COUNT(c.category_id) AS count, c. category_id, c.parent_id, cd.name, p.product_id FROM category c L
require 'db.php';
$result = mysql_query("SELECT COUNT(c.category_id) AS count, c. category_id, c.parent_id, cd.name, p.product_id FROM category c
LEFT JOIN category_description AS cd ON (cd.category_id=c.category_id)
LEFT JOIN product_to_category AS ptc ON (ptc.category_id=c.category_id)
LEFT JOIN product AS P ON (p.product_id=ptc.product_id)
GROUP BY c.category_id
ORDER BY c.parent_id,cd.name") or die (mysql_error());
$menuData = array( 'items' => array(), 'parents' => array() );
while ($menuItem = mysql_fetch_assoc($result)) {
$menuData['items'][$menuItem['category_id']] = $menuItem;
$menuData['parents'][$menuItem['parent_id']][] = $menuItem['category_id'];
}
function buildMenu($parentId, $menuData) {
$html = '';
if (isset($menuData['parents'][$parentId]))
{
$html = '<ul>';
foreach ($menuData['parents'][$parentId] as $itemId) {
$iCount = ($menuData['items'][$itemId]['product_id'] != NULL) ? $menuData['items'][$itemId]['count'] : '0';
$html .= '<li>' . $menuData['items'][$itemId]['name'] . ' (' . $iCount . ') ';
$html .= buildMenu($itemId, $menuData);
$html .= '</li>';
}
$html .= '</ul>';
}
return $html;
}
echo buildMenu(0, $menuData);
电流输出:
Dell (0)
--Computer(0)
---DataCable(1)
----Extra Sub (0)
我认为你的查询返回了错误的结果。使用
打印“”;打印(菜单数据);打印“”调用buildMenu()函数之前,请先编写>代码,然后查看查询是否返回正确的数据。我认为这应该让您更接近正确的方向:
foreach ($menuData['parents'][$parentId] as $itemId) {
$menu = buildMenu($itemId, $menuData);
$item = $menuData['items'][$itemId];
$iCount = ($item['product_id'] != NULL) ? $item['count'] : '0';
$menuData['items'][$parentId]['count'] += $iCount;
$html .= '<li>' . $item['name'] . ' (' . $iCount . ') ';
$html .= $menu
$html .= '</li>';
}
foreach($menuData['parents'][$parentId]作为$itemId){
$menu=buildMenu($itemId,$menuData);
$item=$menuData['items'][$itemId];
$iCount=($item['product_id']!=NULL)?$item['count']:'0';
$menuData['items'][$parentId]['count']+=$iCount;
$html.=''.$item['name'.'。('.$iCount.');
$html.=$menu
$html.=' ';
}
通过重新排序,然后将当前项的计数添加到父项的计数,可以确保在输出iCount时,它也将包括所有子项的计数
我还为$menuData['items'][$itemId]
使用了一个临时变量。因为您只需要在$menuData上进行三次数组查找,所以它的效率可能不会更高,但更易于阅读。我得到了每个类别的正确计数,但我的问题是它首先呈现TopCat,然后从那里开始向下。所以当我倒下的时候,我永远都无法得到最高级别的计数。我是否需要另一个先计算所有内容的递归函数?或者这个问题的最佳实践是什么?
foreach ($menuData['parents'][$parentId] as $itemId) {
$menu = buildMenu($itemId, $menuData);
$item = $menuData['items'][$itemId];
$iCount = ($item['product_id'] != NULL) ? $item['count'] : '0';
$menuData['items'][$parentId]['count'] += $iCount;
$html .= '<li>' . $item['name'] . ' (' . $iCount . ') ';
$html .= $menu
$html .= '</li>';
}