duaj39673 2017-03-22 18:27
浏览 47
已采纳

递归数组清理

I have a function called combined which is going to loop through an array of orders. It is specifically searching for someone who placed more than 1 order and matches based on the customer's name and address line 1. If the customer places 2 orders this will catch them and combine them however if they have 3 or more if only catches 2. When I recursively call the function I get an invalid offset error which I do not understand as I thought the array index would refresh on every function call?

function combined(Array $all) {
//find any matching single orders and combine
$count = count($all);
$combinedorder = array();
for($i=1; $i < $count; $i++) {
    for($j=1; $j < $count; $j++) {
        //if order # is not the same
        if(strcasecmp($all[$i][0], $all[$j][0]) !== 0){ 
          //if name matches
            if(strcasecmp($all[$i][2], $all[$j][2]) == 0) {
              //if address line 1 matches
                if(strcasecmp($all[$i][3], $all[$j][3]) == 0) {
                    $combinedorder[] = array('ordernos' => array($all[$i][0], $all[$j][0]), $all[$i][1], $all[$i][2], $all[$i][3], $all[$i][4], $all[$i][5], $all[$i][6], $all[$i][7], $all[$i][8], $all[$i][9], $all[$i][10], 'orders' => array($all[$i][11], $all[$j][11]));

                    unset($all[$i]);
                    unset($all[$j]);

                    $all = array_merge($all, $combinedorder);
                    $all = array_values($all);
                    reset($all);
             //this recursive call does not work. undefined offset error
                    combined($all);
                }
             }
          }
    }
}
return $all;

}

  • 写回答

1条回答 默认 最新

  • doucuyu2259 2017-03-22 18:41
    关注

    You need to re-index the array. You are deleting some of the indexes with unset($all[$i]) and unset($all[$j]). So when the function calls itself and your loop hits the index that you deleted you get the invalid offset error.

    To fix it just add this code after you unset some of the indexes to reset the keys of the array.

    $all = array_values($all);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测