本文介绍了对多维数组(php)中的特定值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的多维数组:
I got a multidimensional array like this:
Totalarray
(
[0] => Array
(
[city] => NewYork
[cash] => 1000
)
[1] => Array
(
[city] => Philadelphia
[cash] => 2300
)
[2] => Array
(
[city] => NewYork
[cash] => 2000
)
)
我想对具有相同value [city]的子数组的值[cash]求和,并获得一个像这样的数组:
and I'd like to sum the value [cash] of the sub-arrays who got the same value[city] and obtain an array like this:
Totalarray
(
[0] => Array
(
[city] => NewYork
[cash] => 3000
)
[1] => Array
(
[city] => Philadelphia
[cash] => 2300
)
)
我该怎么办?
推荐答案
尝试以下代码:
<?php
$arr = array(
array('city' => 'NewYork', 'cash' => '1000'),
array('city' => 'Philadelphia', 'cash' => '2300'),
array('city' => 'NewYork', 'cash' => '2000'),
);
$newarray = array();
foreach($arr as $ar)
{
foreach($ar as $k => $v)
{
if(array_key_exists($v, $newarray))
$newarray[$v]['cash'] = $newarray[$v]['cash'] + $ar['cash'];
else if($k == 'city')
$newarray[$v] = $ar;
}
}
print_r($newarray);
输出:
Array
(
[NewYork] => Array
(
[city] => NewYork
[cash] => 3000
)
[Philadelphia] => Array
(
[city] => Philadelphia
[cash] => 2300
)
)
这篇关于对多维数组(php)中的特定值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!