douxun7992 2014-08-03 17:54
浏览 89

如何计算foreach循环中的行递归?

This code below returns category tree.

How can I get the count of the products in each category that has sub categories? I mean to sum values in each subcategory.

Until now I succeed to get the count only for the last level of child category:

function menuList($data, $parent = 0 ){
    static $i = 1;
    $tab = str_repeat(' ',$i);
    if($data[$parent]){
        $html = $tab.'<ul id="menu'.$i.'">';
        $i++;
        $count=0;

        foreach($data[$parent] as $v){
            $id = $v->id;
            $categoryname=$v->bg_category;
            if(in_array($id, $_SESSION['active_product_categories'])){
                 $q='select distinct product_id from products_to_categories where category_id="'.$id.'"';
                 $res=mysql_query($q) or die());
                 $num_rows=mysql_num_rows($res);
                 $count='( '.$num_rows.' )';
            }
            $child = menuList($data, $v->id);
            $html .= $tab.'<li>';
            $html .= '<a href="'.$v->WebSite.'/shop/index.php?offers='.$id.'">'.$categoryname.' '.$count.' </a>';

            if($child){
                $i–;
                $html .= $child;
                $html .= $tab;
            }
            $html .= '</li>';
        }
        $html .= $tab.'</ul>';
        return $html;
    } else {
        return false;
    }
}

$query = mysql_query('select * from products_categories where visible="1" group by bg_category order by bg_category ASC');

while($r=mysql_fetch_object($query)){
    $data[$r->parent][] = $r;
}

$menu = menuList($data);
echo $menu;

Please have a look at the screenshot.

Here is the screenshot: http://tinypic.com/view.php?pic=zwgvoz&s=8#.U957sizlrDc

http://oi59.tinypic.com/zwgvoz.jpg

  • 写回答

2条回答 默认 最新

  • doushenjia8514 2014-08-03 18:29
    关注

    If I were you, I would try to write two classes, below I've added examples in pseudo code:

    Class Menu
    {
      private $aSubMenus
      public function __construct()
      public function getNumberOfItems()
      public function addMenuItem()
      public function getHTML()
      public function load($menuID)
    }
    
    Class MenuItem
    {
      public function __construct()
      public function getHTML()
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器