Sum Specific Values in a Multidimensional Array (Php)

sum specific values in a multidimensional array (php)

Try below code:

<?php

$arr = array(
array('city' => 'NewYork', 'cash' => '1000'),
array('city' => 'Philadelphia', 'cash' => '2300'),
array('city' => 'NewYork', 'cash' => '2000'),
);

$newarray = array();
foreach($arr as $ar)
{
foreach($ar as $k => $v)
{
if(array_key_exists($v, $newarray))
$newarray[$v]['cash'] = $newarray[$v]['cash'] + $ar['cash'];
else if($k == 'city')
$newarray[$v] = $ar;
}
}

print_r($newarray);


Output:

Array
(
[NewYork] => Array
(
[city] => NewYork
[cash] => 3000
)

[Philadelphia] => Array
(
[city] => Philadelphia
[cash] => 2300
)

)


Demo:
http://3v4l.org/D8PME

Sum values of multidimensional array by key without loop

You need to couple it with array_map() to select the f_count column first:

array_sum(array_map(function($item) { 
return $item['f_count'];
}, $arr));

Nowadays you can replace the inner function with array_column():

array_sum(array_column($arr, 'f_count'));

Of course, internally, this performs a double loop; it's just that you don't see it inside the code. You could use array_reduce() to get rid of one loop:

array_reduce($arr, function(&$res, $item) {
return $res + $item['f_count'];
}, 0);

However, if speed is the only interest, foreach remains the fastest:

$sum = 0;
foreach ($arr as $item) {
$sum += $item['f_count'];
}

This is thanks to the "locality" of the variables that you're using, i.e. there are no function calls used to calculate the final sum.

Multi dimensional array, sum values of the same key

You can use the dirver and date as a key, Demo

$result = [];
foreach($array as $v){
$key = $v["driver"] . "_" . $v["date"];
if(isset($result[$key])){
$result[$key]["distance"] += $v["distance"];
}else{
$result[$key] = $v;
}
}
$result = array_values($result);

Sum values from a multidimensional array in PHP

Please, always share with us what you have tried.

It help us a lot.

You can use:

$arr = [['name' => "Banana", 'quantity' => 124], ['name' => "Cherry", 'quantity' => 24], ['name' => "Apple", 'quantity' => 224]];

$sum = 0;
foreach ($arr as $item) {
$sum += $item['quantity'];
}

Or (PHP 5.5+):

$sum = array_sum(array_column($arr, 'quantity'));

php Sum specific value from multidimensional array

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

PHP Sum value of specific key with the same ID inside n numbers of arrays in array

resolved

    $result = array();
foreach($array as $k => $v) {
$id = $v['id'];
$result[$id][] = $v['quantity'];
}

$new = array();
foreach($result as $key => $value) {
$new[] = array('id' => $key, 'quanity' => array_sum($value));
}
echo '<pre>';
print_r($new);
?>

Calculate the sum of multidimensional array with same index or different indexes

Try the following example:

$sum = [];

foreach($a as $item) {
foreach($item as $key => $value) {
if (!isset($sum[$key])) $sum[$key] = 0;
$sum[$key] += $value;
}
}

print_r($sum);

If all items have the same keys:

$sum = array_fill_keys(array_keys(reset($a)), 0);

foreach($sum as $key => &$value) {
$value = array_sum(array_column($a, $key));
}

print_r($sum);

php function to sum values from multi dimensional array

As always, no need to over-engineer, if you know the structure, just iterate trough the values, and sum them up, this is how I would do that.

This way you can add many other marketplace and dates without later modifying the code.

<?php
$results = [
'2020-09-06' => [
'Etsy' => ['total_orders' => 2, 'total_stickers' => 3, 'total_value' => 7.8300000000000001],
'Woo' => ['total_orders' => 10, 'total_stickers' => 20, 'total_value' => 100.38],
'eBay' => ['total_orders' => 17, 'total_stickers' => 18, 'total_value' => 67.359999999999999],
],
'2020-09-07' => [
'Etsy' => ['total_stickers' => 8, 'total_orders' => 4, 'total_value' => 34.920000000000002],
'Woo' => ['total_stickers' => 9, 'total_orders' => 3, 'total_value' => '52.90'],
'eBay' => ['total_stickers' => 23, 'total_orders' => 21, 'total_value' => 58.030000000000001],
]
];

$total = ['total_stickers' => 0, 'total_orders' => 0, 'total_value' => 0];

foreach ($results as $k => $v){
foreach ($v as $k1 => $v1){
$total['total_stickers'] += $v1['total_stickers'];
$total['total_orders'] += $v1['total_orders'];
$total['total_value'] += $v1['total_value'];

}
}

var_dump($total);
/*
* array(3) {
["total_stickers"]=>
int(81)
["total_orders"]=>
int(57)
["total_value"]=>
float(321.42)
}
* */

How to sum all column values in multi-dimensional array?

$sumArray = array();

foreach ($myArray as $k=>$subArray) {
foreach ($subArray as $id=>$value) {
$sumArray[$id]+=$value;
}
}

print_r($sumArray);


Related Topics



Leave a reply



Submit