我试图获得成功的数组结果,并开始根据数组中的另一个值对值进行计算。
首先,我想对这些数组中的每个客户“CSTNOC”的每个数量“TotalQTY”进行求和。
数组正在打印,但我在上一个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;
}
}
发布于 2018-04-09 06:58:44
为什么你要循环$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
,所以不管它是什么,都可以使用。
发布于 2018-04-09 06:50:44
您正在使用相同的变量$dealerRow两次。在以下位置:
while($dealerRow = odbc_fetch_array($dealerRslt)){
和在
foreach($dealerResult['cstnoc'] as $dealerRow){
尝试在foreach中使用另一个名称。
发布于 2018-04-09 06:58:26
简单的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);
https://stackoverflow.com/questions/49735729
复制相似问题