基于其他值的数组的和值

时间:2014-06-16 08:55:40

标签: php arrays

好吧,我有这个数组$ city:

Array
(
    [0] => Array
        (
            [0] => fr
            [1] => paris
            [2] => FR-J
            [3] => 0
            [4] => 116729
            [5] => 0
            [6] => 0
        )

    [1] => Array
        (
            [0] => fr
            [1] => marseille
            [2] => FR-U
            [3] => 0
            [4] => 12898
            [5] => 0
            [6] => 0
        )

    [2] => Array
        (
            [0] => fr
            [1] => lyon
            [2] => FR-V
            [3] => 0
            [4] => 8608
            [5] => 0
            [6] => 0
        )

    [3] => Array
        (
            [0] => fr
            [1] => nice
            [2] => FR-U
            [3] => 0
            [4] => 6838
            [5] => 0
            [6] => 0
        )

依此类推......我想总结$ city [$ key] [4],并会产生这样的结果:

 Array
(
    [0] => Array
        (
            [0] => FR-J
            [1] => 116729

        )

    [1] => Array
        (
            [0] => FR-U
            [1] => 19736
        )

    [2] => Array
        (
            [0] => FR-V
            [1] => 8608
        )

以下是我尝试这样做的方法:

$totals = array();
    foreach ($city as $key => $value) {
        if (isset($city[$key][3])){
            $totals[$key][0] = $city[$key][2];
            $totals[$key][1] += (int) $city[$key][4]; \\ <-- this line
        } else {
            $totals[$key][0] = $city[$key][2];
            $totals[$key][1] = (int) $city[$key][4];
        }
    }

但是它生成了这个数组,但是在评论的行中加上了总和Undefined offset: 1。我能做到这一点吗?非常感谢。

4 个答案:

答案 0 :(得分:2)

$sum = [];

foreach($city as $value) {
    if(!isset($sum[$value[2]]))
        $sum[$value[2]] = 0;

    $sum[$value[2]] += $value[4];
}

$results = [];

foreach($sum as $key => $value)
    $results[] = [$key,$value];

print_r($results);

答案 1 :(得分:1)

为什么不先设置它,将其初始化为零。这样你就不会有未定义的索引错误。考虑这个例子:

$new_values = array();
foreach($original_values as $key => $value) {
    if(!isset($new_values[$value[2]][1])) $new_values[$value[2]][1] = 0;
    $new_values[$value[2]][0] = $value[2];
    $new_values[$value[2]][1] += $value[4];
}

$new_values = array_values($new_values);

答案 2 :(得分:1)

这将解决您的问题。

$new_values = array();
foreach($original_values as $key => $value) {
      if(false == isset($new_values[$value[2]][1])) {
             $new_values[$value[2]][1] = 0;
       }

      $new_values[$value[2]][0] = $value[2];
      $new_values[$value[2]][1] += $value[4];
}

$ new_values = array_values($ new_values);

在if语句中也使用bracers,这是我们社区的最佳实践。

答案 3 :(得分:0)

试试这个:

$totals = array();
foreach ($city as $key => $value) {
    $totals[$key][0] = $city[$key][2];
    if(!isset($totals[$key][1])) 
        $totals[$key][1] = 0;
    $totals[$key][1] += (int) $city[$key][4]; 
}