Cnory
Cnory
2017-08-28 09:15
采纳率: 83.3%
浏览 2.1k
已采纳

【PHP】合并二维数组内指定的相同键并计算另一键的和后组成新的二位数组


array(4) {
  [0] => array(5) {
    ["id"] => int(1)
    ["order_num"] => string(11) "20170823-01"
    ["name"] => string(4) "4015"
    ["num"] => int(2000)
    ["time"] => int(1503590400)
  }
  [1] => array(5) {
    ["id"] => int(2)
    ["order_num"] => string(11) "20170823-02"
    ["name"] => string(4) "4015"
    ["num"] => int(3000)
    ["time"] => int(1503590400)
  }
  [2] => array(5) {
    ["id"] => int(3)
    ["order_num"] => string(11) "20170823-03"
    ["name"] => string(4) "4123"
    ["num"] => int(1000)
    ["time"] => int(1503590400)
  }
  [3] => array(5) {
    ["id"] => int(4)
    ["order_num"] => string(11) "20170823-04"
    ["name"] => string(4) "4123"
    ["num"] => int(1000)
    ["time"] => int(1503590400)
  }
}

原始数组如上
需要将 ["name"] 相同的合并到一起,且所对应的 ["num"]的值为原始数据中两个值的和
可能有多个相同["name"]
因为是新手,试了很多方法都没实现,想请教大牛们,应该怎么实现?
其他的键可以忽略

最终的结果是这种


array(4) {
  [0] => array(5) {
    ["name"] => string(4) "4015"
    ["num"] => int(5000)
        ["time"] => int(1503590400)
  }
  [1] => array(5) {
    ["name"] => string(4) "4123"
    ["num"] => int(2000)
    ["time"] => int(1503590400)
  }

}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • yi_an
    yi_an 2017-08-29 11:53
    已采纳

    拿好不谢

    $arr = [
        [
            'name'=>111,
            'sum'=>2
        ],
        [
            'name'=>111,
            'sum'=>3
        ],
        [
            'name'=>222,
            'sum'=>5
        ],
    ];
    $tmp = [];
    foreach ($arr as $v) {
        if(!isset($tmp[$v['name']])){
            $tmp[$v['name']]['name'] = $v['name'];
            $tmp[$v['name']]['sum'] = $v['sum'];
        }else{
            $tmp[$v['name']]['name'] = $v['name'];
            $tmp[$v['name']]['sum'] += $v['sum'];
        }
    }
    $out = array_values($tmp);
    var_dump($out);
    
    
    点赞 评论
  • qq_23292875
    Hefei19881002 2017-08-28 09:24

    创建一个map 遍历二维数组拿到name值(作为map的key) 和num值(value) 每遍历拿到一组值的时候判断map中是否存在以这个name作为key的value值 如果不存在放入map 如果存在num相加后覆盖原有value

    点赞 评论

相关推荐