未定义的索引时,分组和总和值在多维数组(Undefined index when Grouping

2019-09-28 02:44发布

我使用下面的代码到组数组$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
    )

Answer 1:

您需要先定义数组:

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'];
        }
    }


Answer 2:

测试存在$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'];
    }
}


文章来源: Undefined index when Grouping and sum values in multidimensional array