我试图获取成功的数组结果,并开始根据数组中的其他值对值进行计算。
首先,我想总结每一个数量' TotalQTY'对于每个客户' CSTNOC'在这些数组中。
数组打印正常但我在上一个foreach循环中收到了未定义的索引错误。
我觉得这很简单但我不确定我的阵列是否结构不正确如果它是我的循环问题。
Array
(
[0] => Array
(
[CSTNOC] => 1976
[FRAMEC] => 1051
[COVR1C] => 1150
[COLR1C] => 99
[START_DATE] => 2018-03-02
[TOTALQTY] => 2
)
[1] => Array
(
[CSTNOC] => 5400
[FRAMEC] => 1051
[COVR1C] => 1150
[COLR1C] => 99
[START_DATE] => 2017-11-10
[TOTALQTY] => 1
)
[2] => Array
(
[CSTNOC] => 5400
[FRAMEC] => 1051
[COVR1C] => 1150
[COLR1C] => 99
[START_DATE] => 2017-04-07
[TOTALQTY] => 2
)
[3] => Array
(
[CSTNOC] => 5400
[FRAMEC] => 1051
[COVR1C] => 1150
[COLR1C] => 99
[START_DATE] => 2018-02-09
[TOTALQTY] => 2
)
[4] => Array
(
[CSTNOC] => 11316
[FRAMEC] => 1051
[COVR1C] => 1150
[COLR1C] => 99
[START_DATE] => 2017-03-03
[TOTALQTY] => 1
)
我基本上希望将这些结果用于excel报告目的:
CSTNOC | TotalQTY
1976 | 2
5400 | 5
11316 | 1
这是脚本的一部分:
$dealerQuery = "
SELECT
cstnoc,
framec,
covr1c,
colr1c,
cast(Left(extd2d, 4)||'-'||substring(extd2d,5,2)||'-'||substring(extd2d, 7,2) as date) as start_date,
sum(orqtyc) as TotalQTY
from table
where cstnoc = {$skuRow['dealer_id']}
AND framec = {$skuRow['frame']}
AND colr1c = {$skuRow['color']}
AND covr1c = {$skuRow['cover']}
AND extd2d >= " . str_replace('-', '', $skuRow['start_date']) . "
group by cstnoc, framec,covr1c,colr1c,extd2d
";
$dealerRslt = odbc_exec($DB2Conn, $dealerQuery);
foreach($skuResult as $skuRow){
while($dealerRow = odbc_fetch_array($dealerRslt)){
$dealerResult[] = $dealerRow;
$sum = 0;
foreach($dealerResult['cstnoc'] as $dealerRow){
$sum += $dealerRow['TotalQTY'];
}
echo $sum;
}
}
答案 0 :(得分:2)
为什么要循环$skuResult
,你从不使用$skuRow
?您可以在查询中SUM
,但对于PHP:
while($dealerRow = odbc_fetch_array($dealerRslt)){
if(!isset($dealerResult[$dealerRow['cstnoc']])) {
$dealerResult[$dealerRow['cstnoc']] = 0;
}
$dealerResult[$dealerRow['cstnoc']] += $dealerRow['TotalQTY'];
}
然后你可以循环显示:
foreach($dealerResult as $cstnoc => $total) {
echo "$cstnoc = $total";
}
您的查询显示小写cstnoc
,但您的结果数组显示大写CSTNOC
,因此请使用它的实际值。
答案 1 :(得分:1)
您使用相同的变量$ dealerRow两次。 上:
while($dealerRow = odbc_fetch_array($dealerRslt)){
并在
foreach($dealerResult['cstnoc'] as $dealerRow){
尝试使用foreach中的其他名称。
答案 2 :(得分:0)
简单foreach
可以解决问题。
$new = array();
foreach($arr as $k=>$v){
$new[$v['CSTNOC']] = isset($new[$v['CSTNOC']]) ? $new[$v['CSTNOC']] + $v['TOTALQTY'] : $v['TOTALQTY'];
}
print_r($new);