Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum arrays while sql->fetch()

Tags:

sql

php

mysql

pdo

My code looks like this:

$sql = $pdo->prepare('SELECT source_clicks,source_impr,source_spend FROM `statistic` WHERE camp_id =? AND date BETWEEN ? AND ?');
$sql->bindColumn('source_clicks',$source_clicks);
$sql->bindColumn('source_impr',$source_impr);
$sql->bindColumn('source_spend',$source_spend);
$sql->execute([$_POST['get_source_stat'],$date[0],$date[1]]);

while ( $sql->fetch()) {
    $data = explode(',',$source_clicks);
    print_r($data);

}

the output i get is:

Array ( [0] => 30 [1] => 30 [2] => 51 [3] => 108 ) Array ( [0] => 30 [1] => 30 [2] => 51 [3] => 228 )

i need to sum this arrays saving their keys and get something like this:

array ([0] => 60 [1] => 60 [2] => 102 [3] => 336)

Can you tell me how can i do it?

like image 810
napoletoss Avatar asked Nov 25 '25 00:11

napoletoss


1 Answers

One way to do this would be to push each exploded $source_clicks value into an array, and then use array_sum and array_column to get the results e.g.

$data = array();
while ($sql->fetch()) {
    $data[] = explode(',',$source_clicks);
}
$sums = array();
foreach (array_keys($data[0]) as $column) {
    $sums[$column] = array_sum(array_column($data, $column));
}
print_r($sums);
like image 177
Nick Avatar answered Nov 27 '25 13:11

Nick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!