生成类别菜单的PHP函数会降低服务器的速度。请帮助优化它 - 也许是recusrsive功能?

时间:2015-02-21 08:06:13

标签: php mysql recursion

我有此功能可生成产品类别菜单。几周前,当我的类别较少时,它工作得很好,但每次添加新类别时,页面加载时间都会越来越长。这是功能:

function getProductCategorieshome(){
$query='select id, bg_category,url from products_categories 
where visible="1" and parent="0" group by bg_category order by bg_category ASC';    
$result=mysql_query($query) or die();    
$num_rows=mysql_num_rows($result);    
if($num_rows){
echo '<ul id="mmenu" class="top-level">';
$htm='';
for($i=0;$i<$num_rows;$i++){
    $row=mysql_fetch_row($result);
    //sub category    
$query="select id,bg_category,parent,url from products_categories 
where visible='1' and parent='".$row[0]."' group by bg_category order by bg_category ASC";
$result1=mysql_query($query) or die();
$num_rows1=mysql_num_rows($result1);
    if($num_rows1>0){
    $sub_htm='';
    for($j=0;$j<$num_rows1;$j++){
    $row1=mysql_fetch_row($result1);    

//here I check if we have products associated with the category so not showing empty categories    

$querys="select distinct pc.id, bg_category,url 
from products_categories pc, products_to_categories ptc, products p 
where pc.id IN(select id from products_categories where 
visible='1' and parent='".$row1[0]."' group by bg_category order by bg_category ASC) and     
pc.id=ptc.category_id and p.id=ptc.product_id and 
p.id not in (".$_SESSION['expired_products'].") 
group by bg_category order by bg_category ASC";
$result1s=mysql_query($querys) or die();    
$num_rows1s=mysql_num_rows($result1s);
if($num_rows1s>0){
$sub_sub_htm='';
for($k=0;$k<$num_rows1s;$k++){
$row1s=mysql_fetch_row($result1s);
$sub_sub_htm.='<li class="li5">'.$row1s[1].'</li>';
}
if(!empty($sub_sub_htm)) $sub_htm.='<li class="li2">'.$row1[1].'<ul class="sub-level">
'.$sub_sub_htm.'</ul></li>';
}else{  
$sub_htm.='<li>'.$row1[1].'</li>';
}   
}
if(!empty($sub_htm)){
$htm.='<li class="li2">'.$row[1].'<ul class="sublevel">'.$sub_htm.'</ul></li>';
}
}else{
$htm.='<li class="li1">'.$row[1].'</li>';
}
}   
    echo $htm;
echo '</ul>';
}
}

我的产品类别表如下:

#id    #bg_category    #parent    #url
1      phones           0         phones
2      smartphones      1         smartphones
3      Nokia            2         nokia
........... and so on

如何优化此功能。如果我不打电话给功能页面平均加载1秒。加载后,加载时间增加到4.5秒。我相信添加更多类别会增加加载时间问题。

很抱歉,如果我无法更好地格式化以下代码!

1 个答案:

答案 0 :(得分:0)

我发现了一个类似的问题,我发布了它的链接! How to display category and subcategory? 无论如何,谢谢你们!