2017-04-27 75 views
0

可以说,我有一个具有水平的记录,它表示一个树层次结构表如何在PHP/CodeIgniter中构建多维嵌套数组?

id   group  parent_group_id 
--------- ---------- --------------- 
1   Parent 1 NULL 
2   Parent 2 NULL 
3   Parent 3 NULL 
4   Child 1  1 
5   Child 2  2 
6   Child 3  2 
7   Child 4  6 

我需要,使其在“顶”,由开始的目标是构建一个递归函数来构建一个多维嵌套数组首先构建parent_group_ids为NULL的行的顶层数组。快进几个迭代,即时通讯期待与像这样

$result = array(
    [0] => array(
     'id' => 1, 
     'group' => 'Parent 1', 
     'parent_group_id' => NULL, 
     'children' => array(
      [0] => array(
       'id' => 4, 
       'group' => 'Child 1' 
       'parent_group_id' => 1, 
       'children' => NULL)), 
    [1] => array(
     'id' => 2, 
     'group' => 'Parent 2', 
     'parent_group_id' => NULL, 
     'children' => array(
      [0] => array(
       'id' => 5, 
       'group' => 'Child 2' 
       'parent_group_id' => 2, 
       'children' => NULL), 
      [1] => array(
       'id' => 6, 
       'group' => 'Child 3' 
       'parent_group_id' => 2, 
       'children' => array(
        [0] => array(
         'id' => 1, 
         'group' => 'Child 4' 
         'parent_group_id' => 6, 
         'children' => NULL))) 

什么是要建立这样的事情最好的办法的目的是结束了?我需要确保它遍历每个“分支”。我猜是什么时候它获得顶级父母的ID,然后继续检查是否存在具有等于来自第一次运行的每个ID的parent_group_id的行。然后,如果发现孩子,请获取这些孩子的ID,然后再次检查孩子是否存在。等等等等,直到它运行出ID来检查。

我不熟悉foreach循环来拉出这样的东西。

回答

1

看看这个源代码。

我觉得这个函数有点类似于你所问的。

public function getAreaTree(array $elements, $parentId = null) { 
    $branch = array(); 

    foreach ($elements as $element) { 

     if ($element['parent_id'] == $parentId) { 

      $children = getAreaTree($elements, $element['id']); 

      if ($children) { 

       $element['children'] = $children; 

      } 

      $branch[] = $element; 
     } 

    } 

    return empty($branch) ? null : $branch; 
} 
+0

好吧,当我在所有的元素getAreaTree(初始调用)的result_array过去了,我得到的是前两个顶级元素和没有孩子/孙子 编辑:没关系,我修改你的代码重命名一些东西并错过重命名。 –

0

你好,我曾在你寻找同样的概念。

使用此代码。这对我来说很有用。

function recursion($parent_id = '') { 
     $categories = array(); 
      $this->db->from('category'); 
      $this->db->where('parent_id', $parent_id); 
      $result = $this->db->get()->result_array(); 

      if(count($result) > 0) { 
       foreach ($result as $c) { 
       $child = $this->recursion($c['category_id']); 
       if($child) { 
        $c ['children']= $child; 
       } 
       $categories[] = $c; 
       } 
      } 
      return $categories; 

    } 

function get_cat() { 
      print_r($this->recursion()); 
    } 

这可以提高预加载所有类别的速度,从而跳过每个新的parent_id的查询。

这个函数做了什么:使用给定的parent_id加载所有类别,遍历所有这些类别并递归地存储数组。

但问题是,这迫使你有一个干净的树形结构你的类别。

希望它能帮助你解决你的问题。