对多维数组中的特定值求和(php)

sum specific values in a multidimensional array (php)(对多维数组中的特定值求和(php))
本文介绍了对多维数组中的特定值求和(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
    )
)

我想对获得相同值[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
        )

)


演示:
http://3v4l.org/D8PME

这篇关于对多维数组中的特定值求和(php)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Multidimensional Array in Twig(Twig 中的多维数组)
Turning multidimensional array into one-dimensional array(将多维数组变成一维数组)
Sum values of multidimensional array by key without loop(无循环按键对多维数组的值求和)
How to quot;flattenquot; a multi-dimensional array to simple one in PHP?(如何“变平一个多维数组到 PHP 中的简单数组?)
Filter multidimensional array based on partial match of search value(基于搜索值部分匹配的过滤多维数组)
Generate json string from multidimensional array data(从多维数组数据生成json字符串)