0

How can I dynamically group the array values and count the sum of each group? This is my current array:

Array ( [0] => Array ( [source] => web [count] => 1 ) 
        [1] => Array ( [source] => web [count] => 1 ) 
        [2] => Array ( [source] => catalog [count] => 1 ) 
        [3] => Array ( [source] => magazine [count] => 1 ) 
        [4] => Array ( [source] => newspaper [count] => 1 ) 
        [5] => Array ( [source] => web [count] => 1 ) 
        [6] => Array ( [source] => newspaper [count] => 1 ) 
        [7] => Array ( [source] => web [count] => 1
)

This is what I'd like to acheive:

Array ( [0] => Array ( [source] => web [count] => 4 ) 
        [1] => Array ( [source] => catalog [count] => 1 ) 
        [2] => Array ( [source] => magazine [count] => 1 ) 
        [3] => Array ( [source] => newspaper [count] => 2 ) 
)
1

1 Answer 1

1

I will proceed like that:

<pre><?php

$arr = array ( array ( 'source' => 'web', 'count' => 1 ), 
               array ( 'source' => 'web', 'count' => 1 ), 
               array ( 'source' => 'catalog', 'count' => 1 ), 
               array ( 'source' => 'magazine', 'count' => 1 ), 
               array ( 'source' => 'newspaper', 'count' => 1 ), 
               array ( 'source' => 'web', 'count' => 1 ), 
               array ( 'source' => 'newspaper', 'count' => 1 ), 
               array ( 'source' => 'web', 'count' => 1)
      );

$temp = array();
foreach ($arr as $v) {
    $temp[$v['source']] += $v['count'];
}

$result = array();
foreach ($temp as $k => $v) {
    $result[] = array( 'source' => $k, 'count' => $v );
}
unset($temp);

print_r($result); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.