Foreach循环来压制重复但添加值

时间:2017-06-06 14:03:55

标签: php

希望有人可以提供帮助。

我有这个数组(这只是一个片段,因为有很多行)。我今天一直在努力做到这一点。

array(628) {
  [0]=>
  array(3) {
    [0]=>
    string(7) "User 1"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [1]=>
  array(3) {
    [0]=>
    string(10) "User 2"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [2]=>
  array(3) {
    [0]=>
    string(9) "User 1"
    [1]=>
    string(2) "10"
    [2]=>
    string(1) "8"
  }
  [3]=>
  array(3) {
    [0]=>
    string(7) "User 3"
    [1]=>
    string(2) "10"
    [2]=>
    string(1) "8"
  }
  [4]=>
  array(3) {
    [0]=>
    string(10) "User 3"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [5]=>
  array(3) {
    [0]=>
    string(9) "User 4"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [6]=>
  array(3) {
    [0]=>
    string(6) "User 1"
    [1]=>
    string(2) "10"
    [2]=>
    string(1) "9"
  }
  [7]=>
  array(3) {
    [0]=>
    string(9) "User 5"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [8]=>
  array(3) {
    [0]=>
    string(9) "User 3"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [9]=>
  array(3) {
    [0]=>
    string(7) "User 1"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [10]=>
  array(3) {
    [0]=>
    string(9) "User 5"
    [1]=>
    string(1) "0"
    [2]=>
    string(1) "0"
  }

正如您所看到的,有重复的"用户"他们不会被称为用户#。我希望任何重复都消失了,但[1]的值增加了收集,[2]的值也加在了一起。

希望信息有用

由于



  [0]=>
  array(3) {
    [0]=>
    string(7) "User 1"
    [1]=>
    string(2) "40"
    [2]=>
    string(2) "37"
  }
  [1]=>
  array(3) {
    [0]=>
    string(10) "User 2"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }
  [2]=>
  array(3) {
    [0]=>
    string(7) "User 3"
    [1]=>
    string(2) "40"
    [2]=>
    string(1) "38"
   }
  [3]=>
  array(3) {
    [0]=>
    string(9) "User 5"
    [1]=>
    string(2) "10"
    [2]=>
    string(2) "10"
  }




1 个答案:

答案 0 :(得分:0)

试试这个:

$arr = array ( 0 => array ('User 1', 10, 10),
                1 => array ('User 2', 10, 10),
                2 => array ('User 1', 10, 10),
                3 => array ('User 2', 10, 10),
                4 => array ('User 1', 10, 10),
                5 => array ('User 3', 10, 10),
); 
$result = array();

foreach($arr as $val){
    $key = array_search($val[0], array_column($result, 0));
    if($key !== false){
        $result[$key][1] = $result[$key][1] + $val[1];
        $result[$key][2] = $result[$key][2] + $val[2];
    }else{
        $result[] = $val;
    }
}
echo "<pre>";print_r($result);

Code Snippet