foreach循环中的PHP递归函数正在下一个循环中添加先前的数据

时间:2017-01-28 12:10:07

标签: php recursion foreach

我循环遍历某些位置,然后调用递归函数来获取这些位置类别和子类别。 发生了什么,该函数将数据作为前一个循环结果的组合返回。我怎么能摆脱这个,请帮助我,我的代码看起来像这样。

foreach ($data as $row) {
   $get_options = categoryWithSubcategories(0, 0,$row['location_id'],$dbConn);
   // here I am passing $row['location_id'] to this function, but it merge prvious data within next loop.
}

递归函数如下。

function categoryWithSubcategories($current_cat_id, $count,$locationId,$dbConn)
{
    static $option_results;
    // if there is no current category id set, start off at the top level (zero)
    if (!isset($current_cat_id)) {
        $current_cat_id =0;
    }
    // increment the counter by 1
    $count = $count+1;
    // query the database for the sub-categories of whatever the parent category is
    $sql =  "SELECT cat_id, cat_name from tbl_category where cat_parent_id = $current_cat_id and locationid=$locationId and delete_flag='0'";
    $stmt =  $dbConn->prepare($sql);
    $result =$stmt->execute();
    $data = $stmt->fetchAll();
    $num_options = $stmt->rowCount();
    if ($num_options > 0) {
        foreach ($data as $categoryList) {
            // if its not a top-level category, indent it to
            //show that its a child category
            if ($current_cat_id!=0) {
                $indent_flag =  ' ';
                for ($x=2; $x<=$count; $x++) {
                    $indent_flag .=  ' >> ';
                }
            }
            $cat_name = $indent_flag.$categoryList['cat_name'];
            $option_results[$categoryList['cat_id']] = $cat_name;
            // now call the function again, to recurse through the child categories
            categoryWithSubcategories($categoryList['cat_id'], $count,$locationId,$dbConn );
        }
    }
    return $option_results;
}

1 个答案:

答案 0 :(得分:1)

在函数categoryWithSubcategories()中 您已将$ option_results定义为static。这就是在每次新迭代中合并/添加函数的结果背后的原因。

你可以试试这个: 1.从$ option_results中删除静态。 2.存储函数categoryWithSubcategories()的结果 在下面的行。

categoryWithSubcategories($categoryList['cat_id'], $count,$locationId,$dbConn );

这可以写成

$option_results = array_merge(categoryWithSubcategories($categoryList['cat_id'], $count,$locationId,$dbConn), $option_results) ;