【问题标题】:PHP - sum values with the same keyPHP - 用相同的键对值求和
【发布时间】:2017-11-07 14:55:46
【问题描述】:

对于每种不同的颜色,用相同的“颜色”对“val”字段求和的最佳方法是什么:

Array
(
    [0] => Array
        (
            [color]=> "red"
            [val]=> 4
        )

    [1] => Array
        (
            [color]=> "green"
            [val]=> 3
        )

    [2] => Array
        (
            [color]=> "blue"
            [val]=> 1
        )

    [3] => Array
        (
            [color]=> "green"
            [val]=> 6
        )

    [4] => Array
        (
            [color]=> "blue"
            [val]=> 2
        )
)

期望的结果:红色:4;绿色:9;蓝色:3。

问候, 埃利奥·费尔南德斯

【问题讨论】:

  • 我确信有一种超级灵巧的方法可以使用array_walk 或回调在一行中执行此操作,但是关于简单循环的可读性还有一些话要说。我会循环它。此外,“最佳”是主观的。就性能而言,这两种方法可能大致相同。

标签: php json sum


【解决方案1】:

我会这样做,使用 foreach 循环:

$temp = [];
foreach($arr as $value) {
    //check if color exists in the temp array
    if(!array_key_exists($value['color'], $temp)) {
        //if it does not exist, create it with a value of 0
        $temp[$value['color']] = 0;
    }
    //Add up the values from each color
    $temp[$value['color']] += $value['val'];
}

【讨论】:

    【解决方案2】:

    您可以使用array_reduce 来获得越来越少的可读代码:

    $array = array
    (
        0 => array("color"=> "red","val"=> 4),
        1 => array("color"=> "blue","val"=> 3),
        2 => array("color"=> "blue","val"=> 1)
    );
    
    function sum($accumulator, $item){
        $accumulator[$item['color']] = $accumulator[$item['color']] ?? 0;
        $accumulator[$item['color']] += $item['val'];
        return $accumulator;
    }
    
    $sum = array_reduce($array, "sum");
    var_dump($sum); // return here array(2) { ["red"]=> int(4) ["blue"]=> int(4) }
    

    还有文档:http://php.net/manual/en/function.array-reduce.php

    【讨论】:

    • 这里没有考虑颜色
    【解决方案3】:

    为了可读性,我会循环播放。

    $output = array();
    foreach($array as $value){
        if(!isset($output[$value['color']])) $output[$value['color']] = 0; //Ensure the value is 0 if it doesn't exist
        $output[$value['color']] += $value['val']; //Add the total for that color
    }
    

    这将返回一个颜色数组来计算总数。

    【讨论】:

    • 我喜欢保持老派风格的简单优雅。干净、直接、切中要害。
    【解决方案4】:

    我个人会用array_reduce 做类似的事情,但如上所述,它可能不是最易读的选项。不过绝对是见仁见智。

    $result = array_reduce($array, function ($carry, $item) {
        $carry[$item['color']] = $carry[$item['color']] ?? 0;
        $carry[$item['color']] += $item['val'];
        return $carry;
    }, []);
    

    https://eval.in/894644

    编辑:修复通知

    【讨论】:

    • array_reduce 比循环快吗?无论哪种方式我都喜欢这个解决方案,但我很好奇:)
    • 无法想象里面有很多东西,但如果我不得不猜测的话,我会说循环可能更快。虽然很明显,除非您谈论的是一个包含 100,000 个项目的数组,否则您不会注意到。
    【解决方案5】:

    为了保持速度,没有 foreach 循环,我会说这样做:

        $array = [
                    [
                        "color" => "red",
                        "val" => "4"
                    ],
                    [
                        "color" => "green",
                        "val" => "3"
                    ],
                    [
                        "color" => "blue",
                        "val" => "1"
                    ],
                    [
                        "color" => "green",
                        "val" => "6"
                    ],
                    [
                        "color" => "blue",
                        "val" => "2"
                    ]
           ];
    
        $array = array_values(array_reduce(
             $array,
    
               function (array $a, array $v) {
                  $k = "".$v['color']."";
                        
                  if (!array_key_exists($k, $a)) {
                      $a[$k] = $v;   
                  } else {
                      $a[$k]['val'] += $v['val'];
                  }
                  return $a;              
              },
           array()                   
        ));
    
    var_dump($array);
    

    【讨论】:

      【解决方案6】:
      $arrays = array( 
               array(
                      "color"=>"red",
                      "val"=>4
               ),
               array( 
                     "color"=>"green",
                     "val"=>3
              )
      );
      foreach ($color as $array) {
          echo $array["color"].": ".$array["val"].";";
      }
      

      【讨论】:

      • 这会到处发出通知。
      猜你喜欢
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 2020-08-23
      • 2018-08-18
      • 2014-04-23
      • 2014-02-26
      • 1970-01-01
      相关资源
      最近更新 更多