Sum数组值相同的关键php

时间:2018-02-07 07:29:09

标签: php arrays sum

如何对具有相同[sub_type]的数组的[value]求和?

Array (
[0] => Array ( [sub_type] => Doctor [value] => 270000.00 )
[1] => Array ( [sub_type] => Doctor [value] => 100000.00 )
[2] => Array ( [sub_type] => Medicine [value] => 280000.00 )
[3] => Array ( [sub_type] => Doctor [value] => 120000.00 )
)

期望的结果:

Array (
[0] => Array ( [sub_type] => Doctor [value] => 490000.00 )
[1] => Array ( [sub_type] => Medicine [value] => 280000.00 )
)

2 个答案:

答案 0 :(得分:2)

也许它不是那么干净,但似乎有效^ _ ^

<?php
$x = [
    ['sub_type' => 'Doctor', 'value' => 270000.00 ],
    ['sub_type' => 'Doctor', 'value' => 100000.00 ],
    ['sub_type' => 'Medicine', 'value' => 280000.00 ],
    ['sub_type' => 'Doctor', 'value' => 120000.00 ],
];

$result = [];

array_walk($x, function($item) use (&$result) {
    if (!isset($result[$item['sub_type']])) {
        $result[$item['sub_type']] = 0;
    }

    $result[$item['sub_type']] += $item['value'];
});

var_dump($result);

$resultFormated = [];
foreach ($result as $key => $value) {
    $resultFormated[] = ['sub_type' => $key, 'value' => $value];
}

var_dump($resultFormated);

结果:

array(2) {
  ["Doctor"]=>
  float(490000)
  ["Medicine"]=>
  float(280000)
}

array(2) {
  [0]=>
  array(2) {
    ["sub_type"]=>
    string(6) "Doctor"
    ["value"]=>
    float(490000)
  }
  [1]=>
  array(2) {
    ["sub_type"]=>
    string(8) "Medicine"
    ["value"]=>
    float(280000)
  }
}

答案 1 :(得分:0)

<?php 
foreach ($ecr_lines as $line) {
      $test [] = array('sub_type' => $line -> sub_type , 'value' => $line -> value) ;
    }
      array_walk ($test, function($item) use (&$result) {
        if (!isset($result[$item['sub_type']])) : $result [$item ['sub_type']] = 0 ; endif;
        $result [$item ['sub_type']] += $item ['value'] ;
      }) ;
      foreach ($result as $key => $value) {
        $resultFormated [] = ['sub_type' => $key,'value' => $value] ;
      }

  foreach ($resultFormated as $row_data) {
    print_r($row_data);echo "<br>";
  }
?>

结果:

Array ( [sub_type] => Doctor / Medis [value] => 490000 )
Array ( [sub_type] => Medicine [value] => 280000 )