0

I've this array actually:

Array
(
    [0] => Array
        (
            [color] => Red
            [count] => 6
        )
    [1] => Array
        (
            [color] => Purple
            [count] => 6
        )
    [2] => Array
        (
            [color] => Red
            [count] => 6
        )
)

How can i create a new array with the sum by color like this:

|--------|-------|
| Color  | Count |
|--------|-------|
| Red    |    12 |
| Purple |     6 |
|--------|-------|

This is what I tried without success:

array_sum(array_map(
    function($item) {
        return $item['color'];
    }, $items)
);

What I'm missing here please ?

Thanks a lot for your help.

4
  • 1
    Your array_map will remove the count and you only get a plain array with color strings, that cannot be summed. You could use a simple loop to build a color map and then adding the counts manually to that single map. Commented Mar 29, 2018 at 13:51
  • agree with @xander you have to loop and use += to add to last value inside loop to get total count for the colours into a new array Commented Mar 29, 2018 at 13:53
  • What version of PHP do you use? Commented Mar 29, 2018 at 13:56
  • @Martin: i'm using PHP 7.0 Commented Mar 29, 2018 at 13:56

3 Answers 3

2

Iterates over $array. Uses color value as array key, and using that to locate what color to increment the count for.

Loop Option:

$result = array();
foreach( $array as $k=>$v ) {
    if( !isset( $result[$v['color']] ) ) $result[$v['color']] = 0;
    $result[$v['color']] += $v['count'];
}

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

Comments

0

You can simply iterate over the array doing what you're asking for:

$array = array(
    array(
        'color' => "Red",
        'count' => 6
    ),
    array(
        'color' => "Purple",
        'count' => 6
    ),
    array(
        'color' => "Red",
        'count' => 6
    )
);

$result = array();
foreach($array as $item){
    $result[$item['color']] = isset($result[$item['color']]) ? $result[$item['color']]+$item['count'] : $item['count'];
}

print_r($result);

Comments

0

You can use array_reduce:

$result = array_reduce($items, function ($carry, $item) {
    $carry[$item['color']] = ($carry[$item['color']] ?? 0) + $item['count'];

    return $carry;
}, []);

Here is the demo.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.