【问题标题】:PHP recursive function inside foreach loop is adding up previous data within next loopforeach 循环中的 PHP 递归函数正在将下一个循环中的先前数据相加
【发布时间】:2017-01-28 20:27:43
【问题描述】:

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

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;
}

【问题讨论】:

  • 您是否考虑过更改 sql 以检索您需要的所有信息?
  • 您没有遗漏退货声明吗? return categoryWithSubcategories($categoryList['cat_id'], $count,$locationId,$dbConn ); 在 foreach 循环内

标签: php recursion foreach


【解决方案1】:

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

你可以试试这个: 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) ;

【讨论】:

  • 你是对的,只是注意到了静态变量。但是您给出的解决方案不起作用。但我有一个想法,我必须解决这个静态变量。
  • 您能否澄清一下为什么它不起作用?是没有给出预期的结果还是抛出了一些错误?
  • 它抛出警告 array_merge() 第一个值不是数组。
  • 我认为如果控制不在这个 if 块中,就会发生这种情况。 “如果($num_options > 0){”。如果你在这个函数的第一行定义 $option_results = array() 就可以解决这个问题。
  • 很高兴为您提供帮助,如果此答案解决了您的问题,请单击答案旁边的复选标记将其标记为已接受。
猜你喜欢
  • 2012-11-19
  • 1970-01-01
  • 2014-05-29
  • 2014-09-29
  • 2023-04-02
  • 2022-07-06
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
相关资源
最近更新 更多