2016-12-05 77 views
0

我想爲每個fid做一個我的pid的父列表。用遞歸函數錯誤創建一個父列表

例子:

fid  pid 
----------- 
1  0 
34  1 
35  34 
36  35 

我試圖讓一個遞歸函數,但我得到的錯誤

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 200704 bytes) in C:\xampp\htdocs\myproject\application\modules\admin\controllers\forums\Forum_management.php on line 91

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32768 bytes) in C:\xampp\htdocs\myproject\system\core\Exceptions.php on line 1

什麼我想才達到的

如果需要獲得parentlist對於fid = 36,則應該能夠回顯35,34,1

Question: How can I use a recursive function so can get pid list for example fid = 36 then should be able to echo 35, 34, 1

public function index() { 
    $results = $this->make_parent_list('36'); 

    echo implode(',', $results); 
} 


public function make_parent_list($fid, $parents = array()) 
{ 
    $this->db->where('fid', $fid); 
    $this->db->where('pid >', '0'); 
    $query = $this->db->get('forum'); 

    if ($query->num_rows() > 0) { 

     foreach($query->result() as $row) { 

      $parents[] = $row->pid; 

      $this->make_parent_list($row->fid, $parents); 

     } 
    } 

    return $parents; 
} 

enter image description here

更新

我現在已經嘗試過下面這種方式,但是當我贊同它在我的索引Message: implode(): Invalid arguments passed

public function make_parent_list($fid) 
{ 

    $sql = "SELECT * FROM forum WHERE fid = '" . $fid . "'"; 

    $query = $this->db->query($sql); 

    $arr = array(); 

    foreach ($query->result() as $row) { 

     if ($row->pid) { 

      $arr[] = $row->pid; 

      $arr[] = $this->make_parent_list($row->pid); 

     } 

    } 

    return $arr; 

} 

public function index() { 
    $results = $this->make_parent_list('36'); 

    foreach ($results as $result) { 
     echo implode(',', $result); 
    } 
} 

回答

0

解決方案

我有現在解決了這之後,但谷歌搜索和閱讀

解決方案的發現這裏How to get all the child and grandchild categories of a parent category in codeigniter?

public functio index() { 

    $all_categories = $this->make_parent_list(36); 

    $arr = array(); 

    foreach ($all_categories as $category) { 
     $arr[] = $category['pid']; 
    } 

    echo implode(',', $arr); 
} 

function make_parent_list($fid) { 
    $forum_data = array(); 

    $forum_query = $this->db->query("SELECT * FROM forum WHERE fid = '" . (int)$fid . "'"); 

    foreach ($forum_query->result() as $forum) { 

     if ($forum->pid > 0) { 

      $forum_data[] = array(
       'pid' => $forum->pid, 
      ); 

      $forum_children = $this->make_parent_list($forum->pid); 

      if ($forum_children) { 
       $forum_data = array_merge($forum_children, $forum_data); 
      }   

     } 
    } 

    return $forum_data; 
}