【问题标题】:how to store data in an array in a recursive function如何在递归函数中将数据存储在数组中
【发布时间】:2016-02-10 09:00:53
【问题描述】:

我做了一个递归函数,我想在每次调用函数时将它返回的数据添加到一个数组中。

这是我当前的实现:

public function getParentCategory($categoryId) {   
    $category = Category::find($categoryId);
    if($category != NULL){
        $catArray[]  = $category->id;
        if($category->parent_category_id != NULL) {
            $this->getParentCategory($category->parent_category_id);
        }
    }
}

我想在每次调用函数时将数据存储在catArray中。

【问题讨论】:

  • 试试这个使用 array_merge() if($category->parent_category_id != NULL){ $catArray = array_merge($catArray, $this->getParentCategory($category->parent_category_id);); }
  • @PhpDeveloper,这不太可能奏效:$catArray 不仅超出范围,甚至在第一次使用时都没有定义。

标签: php arrays recursion


【解决方案1】:

您可以只从函数中返回数据。您还需要将其传递给函数,或者使用默认参数:

public function getParentCategory($categoryId, $catArray = array()) {   
    $category = Category::find($categoryId);
    if ($category != NULL){
        $catArray[]  = $category->id;
        if ($category->parent_category_id != NULL){
            $catArray = $this->getParentCategory($category->parent_category_id, $catArray);
        }
    }
    return $catArray;
}

您可以使用array_unshift() 而不是$catArray[]= 以相反的顺序使用$catArray(和/或在递归返回之后添加$category->id)。

【讨论】:

    猜你喜欢
    • 2014-06-27
    • 1970-01-01
    • 2019-06-19
    • 2016-11-23
    • 1970-01-01
    • 2018-06-15
    • 2014-04-08
    • 2021-08-05
    • 2011-07-25
    相关资源
    最近更新 更多