从Array和PHP中递归查找所有子类别

时间:2015-01-23 06:50:10

标签: php recursion

我从DB中获取了所有类别。

array
  11 => 
    object(stdClass)[19]
      public 'inv_category_id' => string '11' (length=2)
      public 'parent_category_id' => string '0' (length=2)
      public 'name' => string 'Innerwear' (length=9)
      public 'level' => string '3' (length=1)

  40 => 
    object(stdClass)[20]
      public 'inv_category_id' => string '40' (length=2)
      public 'parent_category_id' => string '11' (length=2)
      public 'name' => string 'Dupattas, Scarves & Stoles' (length=26)
      public 'level' => string '3' (length=1)

  38 => 
    object(stdClass)[21]
      public 'inv_category_id' => string '38' (length=2)
      public 'parent_category_id' => string '11' (length=2)
      public 'name' => string 'Athletic Apparel' (length=16)
      public 'level' => string '3' (length=1)

  37 => 
    object(stdClass)[22]
      public 'inv_category_id' => string '37' (length=2)
      public 'parent_category_id' => string '38' (length=2)
      public 'name' => string 'Sweaters' (length=8)
      public 'level' => string '3' (length=1)

我有这个功能来查找类别ID 11的所有子类别

public function get_all_child_categories($cat_id) {

    global $all_categories_details;

    $all_child = array();

    foreach ($all_categories_details as $cat){

        if($cat->parent_category_id  ==  $cat_id){
            $all_child[] = $cat->inv_category_id;

            return self::get_all_child_categories($cat->inv_category_id);
        }
    }

   return $all_child;
}

我正在调用此函数get_all_child_categories($parent_cat_id)(11);

我试过

$all_child =  self::get_all_child_categories($cat->inv_category_id);

$all_child[] =  self::get_all_child_categories($cat->inv_category_id);

但它返回一个空数组。

我无法弄清楚我哪里出错了。

1 个答案:

答案 0 :(得分:2)

试试这个

public function get_all_child_categories($cat_id, $all_child = array()) {

global $all_categories_details;



foreach ($all_categories_details as $cat){

    if($cat->parent_category_id  ==  $cat_id){
        $all_child[] = $cat->inv_category_id;

        $all_child =  self::get_all_child_categories($cat->inv_category_id, $all_child);
    }
}

  return $all_child;
 }