在多维数组中汇总特定值(php)

时间:2015-02-15 15:03:36

标签: php arrays multidimensional-array sum

我有一个像这样的多维数组:

Totalarray
(
[0] => Array
    (
        [city] => NewYork
        [cash] => 1000
    )

[1] => Array
    (
        [city] => Philadelphia
        [cash] => 2300
    )

[2] => Array
    (
        [city] => NewYork
        [cash] => 2000
    )
)

我希望将具有相同值[city]的子阵列的值[cash]相加并获得如下数组:

Totalarray
(
[0] => Array
    (
        [city] => NewYork
        [cash] => 3000
    )

[1] => Array
    (
        [city] => Philadelphia
        [cash] => 2300
    )
)

我该怎么做?

4 个答案:

答案 0 :(得分:2)

使用函数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()
);

答案 1 :(得分:0)

使用任意多个循环(或循环函数)来对值求和是效率低的。

这是一个方法,它使用临时键来构建结果数组,然后在循环终止后重新索引结果数组。

代码:(Demo

{{1}}

答案 2 :(得分:-1)

请尝试以下代码:

<?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

答案 3 :(得分:-1)

试试这个:

 $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)
}