我正在尝试构建一个在foreach循环中找到的多维匹配数组。在一个循环之后,数组是正确的,但在第二个循环中,先前的数组值被覆盖。发生了什么事?
$matches = array();
foreach ($promotions as $promotion) {
$matches = array();
foreach ($saleitems as $saleitem) {
if ($saleitem['PROMO_CODE'] == $promotion['SALES_CODE']) {
$matches[] = array('ID'=>$saleitem['ID'], "LINENO"=>$saleitem['LINE'], "SAVING"=>"0", 'SALEINC'=>$saleitem['SALEINC']);
}
}
//other code with works out discount etc.
$linesarray[] = array("CODE"=>$promotion['CODE'], "LINES"=>$matches);
print_r($linesarray);
echo "<p>";
}
输出:
Array ( [0] => Array ( [CODE] => 5 [LINES] => Array ( [0] => Array ([ID] => 51016 [LINENO] => 4 [SAVING] => 5 [SALEINC] => 15.00 ) [1] => Array ([ID] => 51013 [LINENO] => 3 [SAVING] => 5 [SALEINC] => 15.00 ) ) ) )
Array ( [0] => Array ( [CODE] => 5 [LINES] => Array ( [0] => Array ( [ID] => 51016 [LINENO] => 4 [SAVING] => 5 [SALEINC] => 15.00 ) [1] => Array ([ID] => 43930 [LINENO] => 2 [SAVING] => 0 [SALEINC] => 16.00 ) ) ) [1] => Array ( [CODE] => 7 [LINES] => Array ( [0] => Array ([ID] => 43914 [LINENO] => 1 [SAVING] => 6 [SALEINC] => 16.00 ) [1] => Array ([ID] => 43930 [LINENO] => 2 [SAVING] => 6 [SALEINC] => 16.00 ) ) ) )
正如您所看到的,LINENO 3已被第二个循环替换为第一个数组。为什么呢?
答案 0 :(得分:1)
循环内的$matches = array();
将重新初始化数组。循环前的$matches = array();
很好。
答案 1 :(得分:0)
$matches[] = array('ID'=>$saleitem['ID'], "LINENO"=>$saleitem['LINE'], "SAVING"=>"0", 'SALEINC'=>$saleitem['SALEINC']);
我看到您已修复"SAVING"=>"0"
,但您的输出有其他结果 [SAVING] => 5
您是否再次运行了代码?
您应该向我们提供$promotions
和$saleitems
数组。