问题
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)
?
Code
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'];
}
}
EDIT
$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
will be as show below
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
)
)
回答1:
You need to define the array first:
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'];
}
}
回答2:
Test existence of $result
array indexes too.
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'];
}
}
来源:https://stackoverflow.com/questions/38607559/undefined-index-when-grouping-and-sum-values-in-multidimensional-array