在多维数组中对值进行分组和求和时未定义的索引 [英] Undefined index when Grouping and sum values in multidimensional array
本文介绍了在多维数组中对值进行分组和求和时未定义的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用下面的代码按 currency 将数组$summary
分组,并获得分组的持续时间和成本的总和.到目前为止,我可以对数组进行分组和求和,但是由于数组单元格$result[$split['currency']]['duration']
和$result[$split['currency']]['cost']
是未定义的,因此我在运行代码时会注意到.如何在不使用error_reporting(0)
的情况下删除通知?
I am using the below code to group the array $summary
by currency and get the sum of grouped duration and cost. So far I am able to group and sum the array but since the array cells $result[$split['currency']]['duration']
and $result[$split['currency']]['cost']
are undefined I am getting notice when I run the code. How can I remove the notice without using error_reporting(0)
?
foreach ($summary as $split) {
if (isset($split['currency'])) {
$result[$split['currency']]['duration'] += $split['duration'];
$result[$split['currency']]['cost'] += $split['cost'];
} else {
$result[0]['duration'] += $split['duration'];
$result[0]['cost'] += $split['cost'];
}
}
编辑
$summary = Array
(
[0] => Array
(
[currency] => SGD
[duration] => 8.00
[cost] => 228.57
)
[1] => Array
(
[currency] => SGD
[duration] => 8.00
[cost] => 228.57
)
[2] => Array
(
[currency] =>
[duration] => 8.00
[cost] =>
)
[3] => Array
(
[currency] => MYR
[duration] => 12.00
[cost] => 342.86
)
[4] => Array
(
[currency] => SGD
[duration] => 8.00
[cost] => 228.57
)
[5] => Array
(
[currency] => MYR
[duration] => 12.00
[cost] => 342.86
)
$result
如下所示
Array
(
[0] => Array
(
[currency] => SGD
[duration] => 24
[cost] => 685.71
)
[1] => Array
(
[currency] => MYR
[duration] => 24
[cost] => 685.72
)
[2] => Array
(
[currency] =>
[duration] => 8
[cost] => 0
)
)
推荐答案
您需要先定义数组:
foreach ($summary as $split) {
if (isset($split['currency'])) {
if (!isset($result[$split['currency']]) {
$result[$split['currency']] = [
'duration' => 0,
'cost' => 0
];
}
$result[$split['currency']]['duration'] += $split['duration'];
$result[$split['currency']]['cost'] += $split['cost'];
} else {
$result[0]['duration'] += $split['duration'];
$result[0]['cost'] += $split['cost'];
}
}
这篇关于在多维数组中对值进行分组和求和时未定义的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文