关联数组,相同键的值:get sums&平均“兄弟”值

时间:2017-03-05 22:37:43

标签: php arrays multidimensional-array sum associative-array

我想扩展在Associative array, sum values of the same key找到的主题。

Table

OP问道:

  

而不是让密钥“会议”重复3次。我想要   只需要一次,然后将3个值合并为一个。

答案是:

 $sum = array_reduce($data, function ($a, $b) {
     isset($a[$b['event']]) ? $a[$b['event']]['budget'] += $b['budget'] : $a[$b['event']] = $b;  
     return $a; });

我有一个包含两个以上值的关联数组。我想使用类似上面的函数,但是将所有键值加在一起,而不仅仅是'预算'。 这是一个反映我情况的例子:

数组如下:

$data = array(
   0 => array(
     'event' => 'Conference',
     'budget' => 3700,
     'people' => 200,
     'rate' => 3000, 
  ),
  1 => array(
    'event' => 'Conference',
    'budget' => 500,
    'people' => 200,
    'rate' => 6000,
  ),
  2 => array(
    'event' => 'Showroom',
    'budget' => 1000,
    'people' => 400,
    'rate' => 30000,
  ),
  3 => array(
    'event' => 'Mission Chez client',
    'budget' => 2000,
    'people' => 200,
    'rate' => 3000,
  ),
  4 => array(
    'event' => 'Séminaire',
    'budget' => 700,
    'people' => 40,
    'rate' => 3000,
  ),
  5 => array(
    'event' => 'Livraison',
    'budget' => 4000,
    'people' => 2,
    'rate' => 3000,
  ),
  6 => array(
    'event' => 'Conference',
    'budget' => 334,
    'people' => 200,
    'rate' => 9000,
  ),
);

如果我使用上面的代码,我将能够将“会议”减少到一个条目,如下所示:

[0] => Array
        (
            [event] => Conference
            [budget] => 4534
            [people] => 200
            [rate] => 5000
        )

预算数字是正确的。但人们认为不是。 我怎么能得到'人'和'预算'的总和,所以 [人物] => 600?

最后,是否可以轻松获得'rate'的平均值值?因此,对于会议,它将是((3000 + 6000 + 9000)/ 3 = 6000)。

总而言之,我正在寻求组织表格以获得如下结果:

[0] => Array
            (
                [event] => Conference  // Key that appears multiple times
                [budget] => 4534  //Sum of all conference budget
                [people] => 600  //Sum of all conference people
                [rate] => 5000  //Average rate of conference
            )

1 个答案:

答案 0 :(得分:2)

尝试

 $sum = array_reduce($data, function ($a, $b) {
     if (!isset($a[$b['event']])) {
          $a[$b['event']] = $b;
     } else {
         $a[$b['event']]['budget'] += $b['budget'];
         $a[$b['event']]['people'] += $b['people'];
         $a[$b['event']]['rate'] += $b['rate'];
     }
 return $a; });

对于平均值,您可以尝试:

 $sum = array_reduce($data, function ($a, $b) {
     if (!isset($a[$b['event']])) {
          $a[$b['event']] = $b;
          $a[$b['event']]['rate_count'] = 1;
          $a[$b['event']]['average_rate'] = array($b['rate']);
     } else {
         $a[$b['event']]['budget'] += $b['budget'];
         $a[$b['event']]['people'] += $b['people'];
         $a[$b['event']]['rate'] += $b['rate'];
         $a[$b['event']]['rate_count'] += 1;
         $a[$b['event']]['average_rate'] = $a[$b['event']]['rate'] / $a[$b['event']]['rate_count'];
     }
 return $a; });