How to Group by and Sum PHP Array

How to GROUP BY and SUM PHP Array?

I have solved it.

public function getDateWiseScore($data) {
$groups = array();
foreach ($data as $item) {
$key = $item['evaluation_category_id'];
if (!array_key_exists($key, $groups)) {
$groups[$key] = array(
'id' => $item['evaluation_category_id'],
'score' => $item['score'],
'itemMaxPoint' => $item['itemMaxPoint'],
);
} else {
$groups[$key]['score'] = $groups[$key]['score'] + $item['score'];
$groups[$key]['itemMaxPoint'] = $groups[$key]['itemMaxPoint'] + $item['itemMaxPoint'];
}
}
return $groups;
}

php group by SUM using multi dimensional array

Why not a simpler

$ts_by_url = array();
foreach($array as $data) {
$ts_by_url[ $data['url_id'] ] += $data['time_spent'];
}

PHP Array Group and sum

You have to iterate over each element and:

  • if there is no key in the sums array, create a key
  • otherwise add the number to the previous sum
<?php

$array = array(
1 => array('great' => 5),
2 => array('great' => 3),
4 => array('bad' => 5),
5 => array('calling' => 40),
6 => array('great' => 3),
);

$sums = array();

foreach ($array as $key => $values) {
foreach ($values as $label => $count) {
// Create a node in the array to store the value
if (!array_key_exists($label, $sums)) {
$sums[$label] = 0;
}
// Add the value to the corresponding node
$sums[$label] += $count;
}
}

// Sort the array in descending order of values
arsort($sums);

print_r($sums);

foreach ($sums as $label => $count) {
print $label.': '.$count.' ';
}

arsort() is used to sort the sums by descending values.

This will print this:

Array
(
[calling] => 40
[great] => 11
[bad] => 5
)
calling: 40 great: 11 bad: 5

Result in Codepad.

Group rows by column and sum another column within groups

You'll have to use array_walk() to modify the array. array_reduce() is to calculate a single value and not to change the array itself.

I would do something like this:

<?php

$array = [
[
'tag_id' => "6291",
'az' => 5,
],
[
'tag_id' => "6291",
'az' => 4,
],
[
'tag_id' => "6311",
'az' => 4,
],
[
'tag_id' => "6427",
'az' => 4,
]
];

$tag_id_indexes = []; // To store the index of the first tag_id found.

array_walk(
$array,
function ($sub_array, $index) use (&$array, &$tag_id_indexes) {
// Store the index of the first tag_id found.
if (!isset($tag_id_indexes[$sub_array['tag_id']])) {
$tag_id_indexes[$sub_array['tag_id']] = $index;
}
else { // This tag_id already exists so we'll combine it.
// Get the index of the previous tag_id.
$first_tag_id_index = $tag_id_indexes[$sub_array['tag_id']];
// Sum the az value.
$array[$first_tag_id_index]['az'] += $sub_array['az'];
// Remove this entry.
unset($array[$index]);
}
}
);

print "The reduced array but with the original indexes:\n" . var_export($array, true) . "\n";

// If you want new indexes.
$array = array_values($array);

print "The reduced array with new indexes:\n" . var_export($array, true) . "\n";

You can test it here: https://onlinephp.io/c/58a11

This is the output:

The reduced array but with the original indexes:
array (
0 =>
array (
'tag_id' => '6291',
'az' => 9,
),
2 =>
array (
'tag_id' => '6311',
'az' => 4,
),
3 =>
array (
'tag_id' => '6427',
'az' => 4,
),
)
The reduced array with new indexes:
array (
0 =>
array (
'tag_id' => '6291',
'az' => 9,
),
1 =>
array (
'tag_id' => '6311',
'az' => 4,
),
2 =>
array (
'tag_id' => '6427',
'az' => 4,
),
)

Group rows of data and in each group sum one column and concatenate another column

I would create an intermediary array which groups into array keys by id first, then use that to call combinations of array_column() with array_sum() and implode() to produce your sum value and combined name string.

$temp_array = [];
foreach ($the_array as $init) {
// Initially, group them on the id key as sub-arrays
$temp_array[$init['id']][] = $init;
}

$result = [];
foreach ($temp_array as $id => $arr) {
// Loop once for each id ($temp_array has 2 elements from your sample)
// And add an element to $result
$result[] = [
'id' => $id,
// Sum the value subkeys
// array_column() returns just the key 'value' as an array
// array_sum() adds them
'value' => array_sum(array_column($arr, 'value')),
// implode the name subkeys into a string
'name' => implode(',', array_column($arr, 'name'))
];
}

print_r($result);
Array
(
[0] => Array
(
[id] => 1
[value] => 60
[name] => apple,orange,banana
)

[1] => Array
(
[id] => 2
[value] => 300
[name] => car,bicycle
)

)

Group multidimensional array by key and sum values in PHP

I would do all the necessary math in the loop that reads the data from the database. Something like this:

$ratings = array();
while ($row = $result->fetch_assoc()) {
$name = $row['name'];
if (!isset($ratings[$name])) {
$ratings[$name] = array('count' => 1, 'sum' => $row['rating']);
}
else {
$ratings[$name]['count']++;
$ratings[$name]['sum'] += $row['rating'];
}
}

Then you can just output your table like so:

echo "<table>";
foreach ($ratings as $name => $r) {
echo "<tr><td>$name</td><td>" . round($r['sum'] / $r['count'], 1) . "</td></tr>";
}
echo "</table>";

PHP getting sum of values group by key in array

public function getGroupByData($data) {
$groups = array();
foreach ($data as $item) {
$key = $item['product_id'];
if (!array_key_exists($key, $groups)) {
$groups[$key] = array(
'id' => $item['product_id'],
'gross_weight' => $item['gross_weight'],
'net_weight' => $item['net_weight'],
);
} else {
$groups[$key]['gross_weight'] = $groups[$key]['gross_weight'] + $item['gross_weight'];
$groups[$key]['net_weight'] = $groups[$key]['net_weight'] + $item['net_weight'];
}
}
return $groups;
}

Php Arrays Sum Group By

Try something like this:

<?php

$data = Array (
Array ( 0 => '18', 1 => '1,07' ),
Array ( 0 => '8', 1 => '0,44' ),
Array ( 0 => '8', 1 => '0,67' ),
Array ( 0 => '18', 1 => '0,55' ),
Array ( 0 => '18', 1 => '0,19' ),
Array ( 0 => '8', 1 => '0,48' ),
Array ( 0 => '18', 1 => '2,59' ),
Array ( 0 => '8', 1 => '0,15' ),
Array ( 0 => '18', 1 => '12,97' )
);

// predefine array
$data_summ = array();
foreach ( $data as $value ) {
$data_summ[ $value[0] ] = 0;
}

foreach ( $data as $list ) {
$number = str_replace( ",", ".", $list[1] ) * 1;
$data_summ[ $list[0] ] += (float)$number;
}

?>

Output of $data_summ:

Array
(
[8] => 1.74
[18] => 17.37
)

If I understand you correctly.

How to group an array by multiple keys and sum the result in php

If you don't want to leverage the database you can just iterate over your data set, group and calculate averages

$csv = [
['user' => 'user1', 'acct_num' => '1', 'value' => 32],
['user' => 'user1', 'acct_num' => '1', 'value' => 2],
['user' => 'user1', 'acct_num' => '2', 'value' => 32],
['user' => 'user1', 'acct_num' => '2', 'value' => 32],
['user' => 'user2', 'acct_num' => '1', 'value' => 312],
['user' => 'user2', 'acct_num' => '1', 'value' => 320],
];

$subtotals = []; // totals per account
$totals = []; // totals per user
$results = [];

foreach($csv as $row) {
list($user, $acct_num, $value) = array_values($row);

$subtotal = isset($subtotals[$user][$acct_num]) ? $subtotals[$user][$acct_num] : 0;
$subtotals[$user][$acct_num] = $subtotal + $value;

$total = isset($totals[$user]) ? $totals[$user] : 0;
$totals[$user] = $total + $value;
}

foreach ($subtotals as $user => $acct_nums) {
foreach ($acct_nums as $acct_num => $value) {
$total = $totals[$user];
$avg = $value / $total;

$results[] = compact('user', 'acct_num', 'value', 'total', 'avg');
}
}

print_r($results);

Here is a demo

Output:


Array
(
[0] => Array
(
[user] => user1
[acct_num] => 1
[value] => 34
[total] => 98
[avg] => 0.3469387755102
)

[1] => Array
(
[user] => user1
[acct_num] => 2
[value] => 64
[total] => 98
[avg] => 0.6530612244898
)

[2] => Array
(
[user] => user2
[acct_num] => 1
[value] => 632
[total] => 632
[avg] => 1
)

)

PHP: group array of objects by id, while suming up object values

i hope this answer help you
first i will change objects to array and return the result to array again

 $values =[
[
"id"=> "xx",
"points"=> 25
],
[
"id"=> "xx",
"points"=> 40
],
[
"id"=> "xy",
"points"=> 40
],
];
$res = array();
foreach($values as $vals){
if(array_key_exists($vals['id'],$res)){
$res[$vals['id']]['points'] += $vals['points'];
$res[$vals['id']]['id'] = $vals['id'];
}
else{
$res[$vals['id']] = $vals;
}
}
$result = array();
foreach ($res as $item){
$result[] = (object) $item;
}

output enter image description here



Related Topics



Leave a reply



Submit