简体   繁体   中英

php Sum specific value from multidimensional array

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM