我有一个名为$ results的数组,我需要将每月的Total_Sales相加。我有下面的代码,给我我需要的结果,但我也得到通知。如何改进代码?
array(4) {
[0]=>
array(3) {
["Month"]=>
string(1) "1"
["Country"]=>
string(2) "AU"
["Total_Sales"]=>
string(7) "9095.70"
}
[1]=>
array(3) {
["Month"]=>
string(1) "1"
["Country"]=>
string(2) "CA"
["Total_Sales"]=>
string(9) "113993.00"
}
[2]=>
array(3) {
["Month"]=>
string(1) "2"
["Country"]=>
string(2) "AU"
["Total_Sales"]=>
string(7) "7393.65"
}
[4]=>
array(3) {
["Month"]=>
string(1) "2"
["Country"]=>
string(2) "CA"
["Total_Sales"]=>
string(9) "100279.43"
}
到目前为止,这是我的代码。它返回的数组是我需要的结果,但我得到了通知
$newarr=array();
foreach($results as $value) {
$Month = $value['MONTH'];
$Total_Sales = $value['Total_Sales'];
array_key_exists( $Month, $newarr ) ? $newarr[$Month]['MONTH'] = $Month : $newarr[$Month]['MONTH'] = 0;
array_key_exists( $Month, $newarr ) ? $newarr[$Month]['Total_Sales']+=$Total_Sales : $newarr[$Month]['Total_Sales'] = 0;
}
array(2) {
[1]=>
array(2) {
["MONTH"]=>
string(1) "1"
["Total_Sales"]=>
float(123088.7)
}
[2]=>
array(2) {
["MONTH"]=>
string(1) "2"
["Total_Sales"]=>
float(107673.08)
}
注意:未定义的索引:第120行的/var/www/html/analytics/views/sales_year_line_data.php中的Total_Sales
注意:未定义的索引:第120行的/var/www/html/analytics/views/sales_year_line_data.php中的Total_Sales
答案 0 :(得分:0)
出现此警告是因为在第一次循环时,$newarr[$Month]['Total_Sales']
未设置,因此不允许使用射击总和,所以请按以下方式执行 -
foreach($results as $value) {
$Month = $value['MONTH'];
$Total_Sales = $value['Total_Sales'];
array_key_exists( $Month, $newarr ) ?
$newarr[$Month]['MONTH'] = $Month : $newarr[$Month]['MONTH'] = 0;
array_key_exists( $Month, $newarr ) ?
$newarr[$Month]['Total_Sales']=
(isset($newarr[$Month]['Total_Sales'])?$newarr[$Month]['Total_Sales']:0)
:$Total_Sales :
$newarr[$Month]['Total_Sales'] = 0;
}