我使用以下代码按货币对数组$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
)
)
答案 0 :(得分:1)
您需要先定义数组:
$apply already in progress
答案 1 :(得分:1)
也测试$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'];
}
}
答案 2 :(得分:0)
我不明白需要额外的条件块。
使用 currency
作为临时键。在第一次遇到 currency
时,存储整行。否则,将当前迭代的 duration
和 cost
添加到存储的组中。完成循环后,使用 array_values()
重新索引数组。
代码:(Demo)
$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,
),
)