我有一个多维数组是这样的:
Totalarray
(
[0] => Array
(
[city] => NewYork
[cash] => 1000
)
[1] => Array
(
[city] => Philadelphia
[cash] => 2300
)
[2] => Array
(
[city] => NewYork
[cash] => 2000
)
)
我想总结与子阵谁得到了相同的值[城市]的值[现金],并获得一个这样的数组:
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
)
)
演示:
http://3v4l.org/D8PME
使用功能array_reduce()
具有相同的项目相结合city
:
$input = array(
array('city' => 'NewYork', 'cash' => '1000'),
array('city' => 'Philadelphia', 'cash' => '2300'),
array('city' => 'NewYork', 'cash' => '2000'),
);
$output = array_reduce(
// Process the input list
$input,
// Add each $item from $input to $carry (partial results)
function (array $carry, array $item) {
$city = $item['city'];
// Check if this city already exists in the partial results list
if (array_key_exists($city, $carry)) {
// Update the existing item
$carry[$city]['cash'] += $item['cash'];
} else {
// Create a new item, index by city
$carry[$city] = $item;
}
// Always return the updated partial result
return $carry;
},
// Start with an empty list
array()
);
使用任何一个以上的环(或循环函数)来总结的值是低效的。
下面是一个使用临时密钥建立结果数组,然后循环终止后重新索引的结果阵列的方法。
编号:( 演示 )
$array=[
['city' => 'NewYork', 'cash' => '1000'],
['city' => 'Philadelphia', 'cash' => '2300'],
['city' => 'NewYork', 'cash' => '2000']
];
foreach($array as $a){
if(!isset($result[$a['city']])){
$result[$a['city']] = $a; // store temporary city-keyed result array (avoid Notices)
}else{
$result[$a['city']]['cash'] += $a['cash']; // add current value to previous value
}
}
var_export(array_values($result)); // remove temporary keys
试试这个:
$sumArray = array();
foreach ($arrTotal as $k=>$subArray) {
foreach ($subArray as $id=>$value) {
$sumArray[$subArray['city']]+=$value;
}
}
var_dump($sumArray);
输出:
array(2) {
["NewYork"]=>
int(3000)
["Philadelphia"]=>
int(2300)
}