Alphonse
Alphonse

Reputation: 671

How to make a sum of array values

I have an array and I iterate through its first 7 values with this function:

function clicksLast7Days($data)
        {
            $path = $data->data->data->clicks;
            $num_loops = 0;
            foreach ($path as $key => $item){
                $num_loops++;
                if($num_loops > 7) break;
                if ($key >= 0) {
                $array[] = $item->clicks;
                }     
            }
           return json_encode($array);   
        }

The array's structure (if it helps) is:

["data"]=>
  object(stdClass)#212 (3) {
    ["status_code"]=>
    int(200)
    ["data"]=>
    object(stdClass)#211 (3) {
      ["days"]=>
      int(30)
      ["total_clicks"]=>
      int(6)
      ["clicks"]=>
      array(30) {
        [0]=>
        object(stdClass)#215 (2) {
          ["clicks"]=>
          int(0)
          ["day_start"]=>
          int(1466395200)
        }
        [1]=>
        object(stdClass)#216 (2) {
          ["clicks"]=>
          int(0)
          ["day_start"]=>
          int(1466308800)
        }
        [2]=>
        object(stdClass)#217 (2) {
          ["clicks"]=>
          int(0)
          ["day_start"]=>
          int(1466222400)
        }
        [3]=>
        object(stdClass)#218 (2) {
          ["clicks"]=>
          int(0)
          ["day_start"]=>
          int(1466136000)
        }
        [4]=>
        object(stdClass)#219 (2) {
          ["clicks"]=>
          int(0)
          ["day_start"]=>
          int(1466049600)
        }
        [5]=>
        object(stdClass)#220 (2) {
          ["clicks"]=>
          int(0)
          ["day_start"]=>
          int(1465963200)
        }
        [6]=>
        object(stdClass)#221 (2) {
          ["clicks"]=>
          int(0)
          ["day_start"]=>
          int(1465876800)
        }
        [7]=>
        object(stdClass)#222 (2) {
          ["clicks"]=>
          int(0)
          ["day_start"]=>
          int(1465790400)
        }

The problem is that by using my function I get an array of elements: [0,0,0,0,0,0,0]. But what I want is to obtain their sum (which in this case is 0), and not an array, just a number.

Upvotes: 0

Views: 56

Answers (1)

DonCallisto
DonCallisto

Reputation: 29912

$clicksArray = $data->data->data->clicks;
$sum = array_sum(
    array_map(
        $clicksArray, 
        function($clickElement) {
            return $clickElement->clicks;
        }
    )
);

What does this mean ?

  • array_sum will sum all values of a certain array. More information here

  • array_map will return all elements of an array, after applying a function (so, basically here, we are returning only clicks attribute

Upvotes: 1

Related Questions