php 使用递归函数填充包含类别和子类别的数组

mqkwyuun  于 2023-02-03  发布在  PHP
关注(0)|答案(2)|浏览(102)

我存储我的类别和子类别在同一个表像这样,每个类别或子类别可以有它自己的子类别

+--------+---------------+---------------+
| id     | title         | parent        |
+--------+---------------+---------------+
|      1 | black         |             0 | 
|      2 | red           |             0 | 
|      3 | dark red      |             2 | 
|      4 | light red     |             2 | 
|      5 | very light red|             4 | 
+--------+---------------+---------------+

我希望将所有类别和子类别存储在一个数组中,使它们保持父子关系
所以我认为递归函数是一种干净的方法,所以这是我想到的最好的方法

function get_categories(){

    $array  =  array();
    $all    = $this->db->get('category' , array('parent'=>0) ); 
   // this query gets all the parent categories ( select * where parent = 0 )

    foreach($all as $a )
    {
        $array[$a->id]['category'] =  $a->title ;
        $array[$a->id]['childs']   = $this->childs( $a->id );
    }

    echo '<pre>';print_r($array); echo '</pre>';

}

 // my recursive function
function childs($parent_id = 0 , $arr = array()){

    $childs =  $this->db->get('category' , array('parent'=>$parent_id ) );
    //  this query :  select * where parent = $parent_id 

    if($childs)
    {
      foreach($childs as $ch)
      {
         $arr[$ch->id][ 'category' ] = $ch->title;
         $arr[$ch->id][ 'childs' ] = $this->childs($ch->id , $arr );
      }
    }

    return $arr ;
}

但是我得到了很多额外的查尔兹为每一个类别,即使没有孩子!以下是在jsfidle(一个!!!:
http://jsfiddle.net/nkxgc4by/

5vf7fwbs

5vf7fwbs1#

当$childs为真时,需要返回$arr;)

}

       return $arr;

只删除您的其他。
对于您的结构:

$arr[$parent_id] = $ch->title;
      $this->childs($ch->id , $arr );

替换为

$arr[$ch->id][ 'category' ] = $ch->title;
      $arr[$ch->id][ 'childs' ] = $this->childs( $ch->id );

那么你的孩子也有同样的结构

a8jjtwal

a8jjtwal2#

$categories = [
  [
    'id' => 1,
    'name' => 'Category 1',
    'parent_id' => null
  ],
  [
    'id' => 2,
    'name' => 'Category 1.1',
    'parent_id' => 1
  ],
  [
    'id' => 3,
    'name' => 'Category 1.2',
    'parent_id' => 1
  ],
  [
    'id' => 4,
    'name' => 'Category 2',
    'parent_id' => null
  ],
  [
    'id' => 5,
    'name' => 'Category 2.1',
    'parent_id' => 4
  ],
];

function buildCategoryTree(array &$elements, $parentId = null) {
  $branch = array();

  foreach ($elements as &$element) {
    if ($element['parent_id'] == $parentId) {
      $children = buildCategoryTree($elements, $element['id']);
      if ($children) {
        $element['children'] = $children;
      }
      $branch[$element['id']] = $element;
      unset($element);
    }
  }
  return $branch;
}
echo "<pre>";
$tree = buildCategoryTree($categories);
print_r($tree);

相关问题