合并具有相同列值的二维数组行并对另一列求和

问题描述 投票:0回答:4

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

[
    ['city' => 'NewYork', 'cash' => 1000],
    ['city' => 'Philadelphia', 'cash' => 2300],
    ['city' => 'NewYork', 'cash' => 2000]
]

我想对共享相同

cash
值的行的值
city
求和以形成具有相同二维结构的结果。

期望的结果:

[
    ['city' => 'NewYork', 'cash' => 3000],
    ['city' => 'Philadelphia', 'cash' => 2300],
]
php arrays multidimensional-array sum grouping
4个回答
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
投票

使用任何一个以上的循环(或循环函数)对值求和是低效的。

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

新代码:(Demo)由于“空合并运算符”而没有迭代函数调用

foreach ($array as $row) {
    $result[$row['city']] = [
        'city' => $row['city'],
        'cash' => ($result[$row['city']]['cash'] ?? 0) + $row['cash']
    ];
}
var_export(array_values($result));

旧代码:(演示

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

输出:

array (
  0 => 
  array (
    'city' => 'NewYork',
    'cash' => 3000,
  ),
  1 => 
  array (
    'city' => 'Philadelphia',
    'cash' => 2300,
  ),
)

0
投票

试试下面的代码:

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


-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)
}
© www.soinside.com 2019 - 2024. All rights reserved.