bhttoan
bhttoan

Reputation: 2736

Get total for value in arrays

I am trying to find a way to allow me to count the number of times a value appears across multiple arrays as well as, for each unique value, the total count.

The data looks like the below:

Array ( [id] => 4383 [score] => 3 )
Array ( [id] => 4382 [score] => 4 )
Array ( [id] => 4381 [score] => 5 )
Array ( [id] => 4383 [score] => 7 )
Array ( [id] => 4383 [score] => 1 )
Array ( [id] => 4382 [score] => 2 )
Array ( [id] => 4381 [score] => 8 )

The above should return:

4383 - 3 - 11
4382 - 2 - 6
4381 - 2 - 13

I have used array_push and created one array called $output and looped using foreach to get a count of the id's using:

foreach($output as $row) {
    $array[$row[0]]++;
}

This returns the correct count of id but I cannot get the total score for each id - I have tried:

foreach($output as $row) {
    foreach($row as $r) {
        $array[$row[0]]=$array[$row[1]]+$array[$r[1]];
    }
}

but it returns zero for everything

Upvotes: 0

Views: 52

Answers (2)

Mooseknuckles
Mooseknuckles

Reputation: 497

$result = array();

foreach ($output as $row) {

    if (!array_key_exists($row[0], $result)) {
        $result[$row[0]] = array("Count" => 1, "Total" => $row[1]);
    }

    else {
        $result[$row[0]]['Count'] += 1;
        $result[$row[0]]['Total'] += $row[1];
    }
}

print_r($result);

Upvotes: 1

xdazz
xdazz

Reputation: 160833

Like below:

$result = array();

foreach ($data as $value) {
  if (!isset($result[$value['id']])) {
    $result[$value['id']] = array('count' => 0, 'sum' => 0);
  }
  $result[$value['id']]['count'] += 1;
  $result[$value['id']]['sum'] += $value['score'];
}

Upvotes: 2

Related Questions