2013-02-16 96 views
0

我正在做商业目录排序的事情,并且需要在类别列表中显示类别的递归父母。我可以做些什么来优化以下功能或其他一些内容以减少内存消耗?

我使用下面的函数为:

public function get_recursive_parents($category_id){ 
     $categories = array(); 
     $res = $this->db->from('categories')->where('cat_id',$category_id)->get()->row_array(); 
     $cat_id = $res['parent_id']; 
     $categories[] = $res; 
     while($cat_id){ 
      $res = $this->db->from('categories')->where('cat_id',$cat_id)->get()->row_array(); 
      $categories[] = $res; 
      $cat_id = $res['parent_id']; 
     } 
     return $categories; 
    } 

我使用这个功能,因为它是在管理网站和一点在管理站点慢可以是也没关系,和管理员将是唯一一所以我可以给它更多的memory.But我觉得限制的内存比300M多为一个呼叫是太多了,仍然得到这样的:

Fatal error: Allowed memory size of 367001600 bytes exhausted (tried to allocate 72 bytes) in /var/www/usmanproject/salesfinder/system/database/DB_active_rec.php on line 2007 

那么,有没有办法让我可以优化上述功能?或者我需要做一些特定的索引或算法优化或其他可能的方式?或者我不再显示所有类别的父母和超级父母(即客户要求看到等级)?或者需要增加内存,因为我已经在一个目录上工作,而且在管理站点上也很慢,所以我猜他们只是使用更多的内存?

任何意见将不胜感激。


这是表模式,它有parent_id,所以它作为递归关系工作。

CREATE TABLE IF NOT EXISTS `categories` (
    `cat_id` int(11) NOT NULL AUTO_INCREMENT, 
    `cat_name` varchar(255) DEFAULT NULL, 
    `cat_title` varchar(255) DEFAULT NULL, 
    `cat_desc` varchar(255) DEFAULT NULL, 
    `cat_text` text, 
    `parent_id` int(11) NOT NULL, 
    `cat_img` varchar(255) DEFAULT NULL, 
    `sort_id` int(11) NOT NULL DEFAULT '1', 
    `last_level` tinyint(4) NOT NULL, 
    PRIMARY KEY (`cat_id`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=221 ; 
+0

您正在使用哪种框架? – ripa 2013-02-16 11:51:48

+0

@ripa我正在使用CodeIgniter – Hafiz 2013-02-16 11:52:33

+0

好。你不会在函数中随时调用get_recursive_parents()。这不是递归调用。 – ripa 2013-02-16 11:57:47

回答

0

尝试使用下面的代码

public function get_recursive_parents($category_id,$categories=array()) 
{ 
    if($category_id!="") 
    { 
     $new_ar1=array(); 
     $fe = $this->db->from('categories')->where('cat_id',$category_id)->get()->row_array(); 
     array_push($new_ar1,$fe["parent_id"]); 
     return $new_ar1; 
    } 
    else 
    { 
     $res = $this->db->from('categories')->get()->row_array(); 
     array_push($categories,$res['parent_id']); 
     $categories[$res['parent_id']]=array(); 

     array_push($categories[$res['cat_id']],get_recursive_parents($res['parent_id'],$categories)); 
    } 

    return $new_ar; 
} 

通话功能

get_recursive_parents($category_id); 

希望它会帮助你

0

问题就解决了,实际上是一个记录,其parent_id是指向它自己的主密钥cat_id。所以这是指向自己,在这种情况下,递归并没有结束。我用while循环,在这种情况下变成无限。

但是在调试过程中,我发现这个帖子很有帮助, http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ 它提供了更好的方法来处理同样的事情。在我的场景中,自我连接在本文中提到很有用。