2 cnory Cnory 于 2017.08.28 17:15 提问

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

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个回答

qq_23292875
qq_23292875   2017.08.28 17:24

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

yi_an
yi_an 回复Cnory: $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);
3 个月之前 回复
Cnory
Cnory 可以麻烦把具体代码发一下吗?
3 个月之前 回复
yi_an
yi_an   2017.08.29 19: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);

Csdn user default icon
上传中...
上传图片
插入图片