Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing objects property in array

Tags:

php

I have an array of objects, and i want to sum value of one of the properties, example:

Array
(
[0] => stdClass Object
    (
        [name] => jon
        [commission] => 5

    )
[1] => stdClass Object
    (
        [name] => smith
        [commission] => 1

    )
[2] => stdClass Object
    (
        [name] => philip
        [commission] => 8

    )
)  

I want to sum all the commissions in the array, result should be 14.

What is a good way for this?

like image 651
user2706762 Avatar asked Nov 25 '13 13:11

user2706762


People also ask

How do you sum multiple objects with the same key in an array?

How do you sum multiple objects with the same key in an array? First iterate through the array and push the 'name' into another object's property. If the property exists add the 'value' to the value of the property otherwise initialize the property to the 'value'.

How do you add elements in array of objects in JS?

The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the end of the array.


3 Answers

array_reduce could be one way to do it; Just simply add your $array

$sum = array_reduce($array, function($carry, $item)
{
    return $carry + $item->commission;
});

var_dump($sum);
like image 196
ilpaijin Avatar answered Oct 15 '22 11:10

ilpaijin


If you are using PHP 5.5

$arr_new = array_sum(array_column($yourarray, 'commission'));
like image 38
Shankar Narayana Damodaran Avatar answered Oct 15 '22 11:10

Shankar Narayana Damodaran


Let's say $arr stores your information. Implement the following function:

function sumProperties(array $arr, $property) {

    $sum = 0;

    foreach($arr as $object) {
        $sum += isset($object->{$property}) ? $object->{$property} : 0;
    }

    return $sum;
}

After that you just have to call sumProperties($array, 'commission').

Furthermore if you have more properties that could be summed, you could replace commission with those properties.

like image 23
ziGi Avatar answered Oct 15 '22 12:10

ziGi