Summing objects property in array

后端 未结 4 1045
难免孤独
难免孤独 2021-01-17 11:44

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

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


        
相关标签:
4条回答
  • 2021-01-17 12:14

    If you are using PHP 5.5

    $arr_new = array_sum(array_column($yourarray, 'commission'));
    
    0 讨论(0)
  • 2021-01-17 12:23

    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.

    0 讨论(0)
  • 2021-01-17 12:39
    $sum = 0;
    foreach($arrObj as $key=>$value){
      if(isset($value->commission))
         $sum += $value->commission;
    }
    echo $sum;
    
    0 讨论(0)
  • 2021-01-17 12:40

    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);
    
    0 讨论(0)
提交回复
热议问题