php array find duplicates, sum them up & delete duplicates

后端 未结 4 1009
无人共我
无人共我 2020-12-01 20:23

i have an array:

Array 
(
[0] => Array
    (
        [setid] => 2
        [income] => 100
    )

[1] => Array
    (
        [setid] => 2
              


        
相关标签:
4条回答
  • 2020-12-01 20:30

    Just create a new array which you make fast adressable by using the setid as key. And reindex the array at the end.

    $result = array();
    foreach ($array as $val) {
        if (!isset($result[$val['setid']]))
            $result[$val['setid']] = $val;
        else
            $result[$val['setid']]['income'] += $val['income'];
    }
    $result = array_values($result); // reindex array
    
    0 讨论(0)
  • 2020-12-01 20:37

    Write your own function, that's no long road at all.

    $result = array_reduce($originalArray, function($memo, $item){
    
      isset($memo[$item['setid']])
        ? $memo[$item['setid']] = $item['income']
        : $memo[$item['setid']] += $item['income'];
      return $memo;
    
    }, []);
    
    0 讨论(0)
  • 2020-12-01 20:40

    You should use the array_unique function that php's official site offers.

    An example:

    <?php
    $input = array("a" => "green", "red", "b" => "green", "blue", "red");
    $result = array_unique($input);
    print_r($result);
    ?>
    

    Output:

    Array
    (
        [a] => green
        [0] => red
        [1] => blue
    )
    

    To sum the duplicated values you can use the array_count_values function:

    <?php
    $array = array(1, "hello", 1, "world", "hello");
    print_r(array_count_values($array));
    ?>
    

    Output would be:

    Array
    (
        [1] => 2
        [hello] => 2
        [world] => 1
    )
    
    0 讨论(0)
  • 2020-12-01 20:47

    This should work:

    $values = array();
    foreach($array as $val) {
        if(isset($values[$val['setid']])) {
            $values[$val['setid']] += $val['income'];
        } else {
            $values[$val['setid']] = $val['income'];
        }
    }
    //all values are now in $values array, keys are setid and values are income
    
    0 讨论(0)
提交回复
热议问题