如何获得特定值数组的总和

时间:2018-06-23 08:23:50

标签: php

我有以下数组

Array
(
    [0] => Array
        (
            [gender] => F
            [thisweektotal] => 3
        )

    [1] => Array
        (
            [gender] => M
            [thisweektotal] => 2
        )

    [2] => Array
        (
            [gender] => Adult
            [thisweektotal] => 1
        )

    [3] => Array
        (
            [gender] => Young Adult
            [thisweektotal] => 4
        )

) 

我只希望本周的性别M和F的总和是5 我尝试了下面的代码,但是我没有得到所有性别F的总和,而我只想要性别M和F的总和。

foreach($analytics_data['this_week'] as $value) 
  {

    if($value['gender']=='M' || $value['gender']=='F')
    {
      $total_this_week_arr = array_column($value['thisweektotal'], 'thisweektotal');
      $this_week_total = array_sum($total_this_week_arr);

    }

  }
 echo "this_week_total=".$this_week_total;

4 个答案:

答案 0 :(得分:0)

由于要循环,因此不需要array_columnarray_sum。您可以:

$this_week_total = 0;

foreach($analytics_data['this_week'] as $value)  {
    if( $value['gender'] == 'M' || $value['gender'] == 'F' )
    {
      $total_this_week_arr = $value['thisweektotal'];
      $this_week_total += $total_this_week_arr ;
    }
}

echo "this_week_total = " .$this_week_total;

答案 1 :(得分:0)

您要遍历数组,只需要一个用于保存和值的变量

$sum = 0;//Your variable which stores the value of sum

foreach($analytics_data['this_week'] as $k=>$arr){
    if($arr['gender']=='F' || $arr['gender']=='M')
    $sum+=$arr['thisweektotal']; //Adding sum to $sum
}

echo $sum;

答案 2 :(得分:0)

这是第三个参数起作用的解决方案using array_column,因为“性别”键中的值没有冲突,可以将数组转换为更简单的求和结构。

$gender = array_column( $array, 'thisweektotal', 'gender' );
$total = $gender['M'] + $gender['F'];

如果有可能丢失密钥,我们可以尝试使用array_intersect_key作为对阵列的“ 白名单过滤器” ...

$gender = array_column( $array, 'thisweektotal', 'gender' );
$filtered = array_intersect_key( $gender, array_flip( array( 'M', 'F' ) ) );
$total = array_sum( $filtered );

答案 3 :(得分:0)

$aInput = [
    [
        "gender" => "F",
        "thisweektotal" => 3,
    ], [
        "gender" => "M",
        "thisweektotal" => 2,
    ], [
        "gender" => "Adult",
        "thisweektotal" => 1,
    ], [
        "gender" => "Young Adult",
        "thisweektotal" => 4,
    ]
];

$iSum = array_reduce($aInput, function($sum, $el) {
    if (in_array($el['gender'], ['F', 'M'])) {
        $sum += $el['thisweektotal'];
    }
    return $sum;
});

var_dump($iSum);