1

I have array like this :

Array
(
    [0] => Array
        (
            [impr] => 800000
            [clicks] => 500
            [ctr] => 0.000625
            [cvr] => 0.04
            [cpc] => 0.14024
            [cpm] => 0.08765
            [cpa] => 3.51
        )

    [1] => Array
        (
            [impr] => 889000
            [clicks] => 600
            [ctr] => 0.000625
            [cvr] => 0.08
            [cpc] => 0.34024
            [cpm] => 0.08765
            [cpa] => 4.41
        )

)

I want to sum that array and get result like this

Array
(
   [impr] => 1689000
   [clicks] => 1100
   [ctr] => 0.0025
   [cvr] => 0.12
   [cpc] => 0.96096
   [cpm] => 0.1753
   [cpa] => 7.92
)

I trying to using

array_sum()

with looping my array to that array_sum, but I getting error like this

array_sum() expects parameter 1 to be array, integer given

And even try looping with foreach and using += for sum the value, but the result is not I want

the result is 800000889000

Can anyone suggest me the better code for getting my result like I want

1
  • did my answer work for you? Commented Jun 1, 2016 at 4:09

1 Answer 1

0

First create an array that will contain the sums:

$sumArray = array(
    "impr" => 0,
    "clicks" => 0,
    "ctr" => 0,
    "cvr" => 0,
    "cpc" => 0,
    "cpm" => 0,
    "cpa" => 0,
);

Then do the calculating:

foreach ($oldArray as $row)
{
    foreach ($rows as $key => $value)
    {
        $sumArray[$key] += $value;
    }
}

Then to view your results, just do:

print_r($sumArray);

NOTE: I am assuming that the keys that you have in your original array don't have the brackets around them, however if the actual key strings do have the brackets, then use the following code for creating $sumArray:

$sumArray = array(
    "[impr]" => 0,
    "[clicks]" => 0,
    "[ctr]" => 0,
    "[cvr]" => 0,
    "[cpc]" => 0,
    "[cpm]" => 0,
    "[cpa]" => 0,
);
Sign up to request clarification or add additional context in comments.

3 Comments

how if I want to make array like this [1689000, 1100, 0.00125, 0.12, 0.48048, 0.1753, 7.92] ?
You could create another foreach loop after my previous code like so: $otherAnswer = array(); foreach ($sumArray as $value){$otherAnswer[] = $value;} What that will do is create another array called $otherAnswer which doesn't contain the $key values (impr, clicks, etc...)
@ArieSastra no problem :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.