Php 同一个键的数组值之和
如何对具有相同[sub_type]的数组的[value]求和Php 同一个键的数组值之和,php,arrays,sum,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 (
[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 )
)
也许它不太干净,但似乎很管用^_^
<?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)
}
}
<?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 )