递归数组清理

时间:2017-03-22 18:27:20

标签: php arrays recursion

我有一个名为combined的函数,它将遍历一个订单数组。它专门搜索根据客户的名称和地址行1放置超过1个订单和匹配的人。如果客户下了2个订单,这将抓住它们并将它们合并,但如果它们有3个或更多,如果只是捕获2.当我递归调用函数时,我得到一个无效的偏移错误,我不明白,因为我认为数组索引会刷新每个函数调用?

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 个答案:

答案 0 :(得分:1)

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