sum specific values in a multidimensional array (php)

sum values in foreach loop php
php sum array values by key
sum of array in php using for loop
php sum variables
multidimensional array sum
php sum total
php average array
php array group by value sum

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

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

How can I do it?

Try below code:

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

Output:

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

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

)

Demo: http://3v4l.org/D8PME

How To Sum Values Of An Array With The Same Key In PHP , How do you sum values of an array with the same key in PHP? array_sum (array $array) : number array_sum () returns the sum of values in an array.

Use function array_reduce() to combine the items having the same 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()
);

PHP, qty , which should give us the result 5 . PHP multidimensional array search by value, In PHP, multidimensional array search refers to searching a value in a multilevel nested array. There are various techniques to carry out this type of search, such PHP search multidimensional array for value and return key If you want to search in multidimensional-array by value and return key.

Using any more than one loop (or looping function) to sum the values is inefficient.

Here is a method that uses temporary keys to build the result array and then reindexes the result array after the loop terminates.

Code: (Demo)

$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

How to Calculate the Sum of Values in an Array in PHP, ($input_array, $column_number, $index_key); Parameters: Out of the three parameters, two are mandatory and one is optional. php,arrays I'm just a beginner in PHP coding. I've been reading through a tutorial, but having some trouble with basic PHP concepts. I've been reading through a tutorial, but having some trouble with basic PHP concepts.

Try this:

 $sumArray = array();

    foreach ($arrTotal as $k=>$subArray) {

        foreach ($subArray as $id=>$value) {
            $sumArray[$subArray['city']]+=$value;
        }

    }

    var_dump($sumArray);

Output:

array(2) {
  ["NewYork"]=>
  int(3000)
  ["Philadelphia"]=>
  int(2300)
}

PHP, Returns the sum of values as an integer or float; 0 if the array is empty. Examples ¶. Example #1 array_sum() examples. <?php $a =  Arrays or sub-arrays in multidimensional arrays can be accessed using multiple dimensions. Dimensions: Dimensions of multidimensional array indicates the number of indices needed to select an element. For a two dimensional array two indices to select an element. Two dimensional array: It is the simplest form of a multidimensional array. It can

array_sum - Manual, Today we look at using these functions and the foreach loop to sum values of an array of the same key in PHP. For the purpose of this article,  PHP - Multidimensional Arrays. A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.

php, how can I sum values of the key NILAI_ANGGARAN Note that NILAI_ANGGARAN key is dynamicarray 1350 gt Array 495 gt Array The column of values to return. This value may be an integer key of the column you wish to retrieve, or it may be a string key name for an associative array or property name. It may also be NULL to return complete arrays or objects (this is useful together with index_key to reindex the array).

PHP array_sum() Function, Example. Return the sum of all the values in the array (52.2+13.7+0.9):. <?php $​  The array_sum () function returns the sum of all the values in the array.

Comments
  • array_reduce() to the rescue!
  • Try this code-only answers are low-value on StackOverflow because they do a poor job of educating/empowering the OP and thousands of future researchers. Please edit this answer to explain what you've done and why it is a good idea.
  • The benefit to using this technique over a foreach() loop is that you don't have to declare an output variable -- I mean you can nest the function call inside of array_values() and then inside of var_export() to display the result on screen. Like this I think the reason some people don't use array_reduce() is because the code block appears more convoluted (just takes a little getting used to).