我使用以下代码按货币对数组$summary
进行分组,并获得分组的持续时间和成本的总和。到目前为止,我可以对数组进行分组和求和,但由于数组单元$result[$split['currency']]['duration']
和$result[$split['currency']]['cost']
是未定义的,所以当我运行代码时,我会注意到这一点。如何在不使用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'];
}
}
还测试$result
数组索引的存在性。
foreach ($summary as $split) {
if (isset($split['currency'])) {
if(!isset($result[$split['currency']])) {
$result[$split['currency']]['duration'] = $split['duration'];
$result[$split['currency']]['cost'] = $split['cost'];
} else {
$result[$split['currency']]['duration'] += $split['duration'];
$result[$split['currency']]['cost'] += $split['cost'];
}
} else {
$result[0]['duration'] += $split['duration'];
$result[0]['cost'] += $split['cost'];
}
}
我不明白是否需要额外的条件块。
使用currency
作为临时密钥。在第一次遇到currency
时,存储整行。否则,将当前迭代的duration
和cost
添加到存储的组中。循环结束后,使用array_values()
重新索引数组。
代码:(演示)
$result = [];
foreach ($array as $row) {
if (!isset($result[$row['currency']])) {
$result[$row['currency']] = $row;
} else {
$result[$row['currency']]['duration'] += $row['duration'];
$result[$row['currency']]['cost'] += $row['cost'];
}
}
var_export(array_values($result));
输出:
array (
0 =>
array (
'currency' => 'SGD',
'duration' => 16.0,
'cost' => 457.14,
),
1 =>
array (
'currency' => NULL,
'duration' => 8.0,
'cost' => NULL,
),
2 =>
array (
'currency' => 'MYR',
'duration' => 24.0,
'cost' => 685.72,
),
)