2013-02-16 101 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/ 它提供了更好的方法來處理同樣的事情。在我的場景中,自我連接在本文中提到很有用。