duandongji2231 2016-07-26 13:11
浏览 48
已采纳

按键对多维数组求和

I have read a lot of answers here on SO but havent been able to sort this out.

I have multidimensional array that looks like this:

Array

(
[0] => Array
    (
        [0] => 
        [1] => 655
    )

[1] => Array
    (
        [0] => IT-82
        [1] => 14
    )

[2] => Array
    (
        [0] => IT-21
        [1] => 5
    )

[3] => Array
    (
        [0] => IT-82
        [1] => 7
    )

[4] => Array
    (
        [0] => 
        [1] => 3
    )

[5] => Array
    (
        [0] => IT-21
        [1] => 4
    )

[6] => Array
    (
        [0] => 
        [1] => 3
    )

[7] => Array
    (
        [0] => IT-21
        [1] => 3
    )

[8] => Array
    (
        [0] => IT-72
        [1] => 7
    )

[9] => Array
    (
        [0] => IT-75
        [1] => 22
    )

[10] => Array
    (
        [0] => IT-75
        [1] => 3
    )
)

I would like to sum the values according to the keys ending with a single array like:

Array 
(
      => 661
IT-82 => 21
IT-21 => 12
IT-82 => 12
IT-72 => 7
IT-75 => 25
)

Tried with

foreach ($array as $k=>$subArray) {
    foreach ($subArray as $id=>$value) {
        $sumArray[$id]+=$value;
    }
}

but this only returned the sum of all the values.

Any help appreciated.

  • 写回答

2条回答 默认 最新

  • dtp0760 2016-07-26 13:20
    关注

    Try:

    $sumArray = array();
    foreach ($array as $k=>$subArray) { //loop through array
      if(isset($sumArray[$subArray[0]]))
        $sumArray[$subArray[0]] += $subArray[1]; // set 0th index as key and 1st as value and add value to current index
      else 
        $sumArray[$subArray[0]] = $subArray[1];
    }
    print_r($sumArray);
    

    Output:

    Array
    (
        [] => 661
        [IT-82] => 21
        [IT-21] => 12
        [IT-72] => 7
        [IT-75] => 25
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?