Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A simple solution to a PHP array problem is needed?

I actually am quite embarrassed to ask such a question but it is one of those days that you spend 10 thousand hours on the simplest of functions and the more you try to solve them the more complicated a solution you get.... I don't want to waste more time so here is the problem.

I have one array:

  $items=array(
    0=> array('name'=>'red','value'=>2),
    1=> array('name'=>'black','value'=>1),
    2=> array('name'=>'red','value'=>3)
  );

And I need a function that detects the identical names and merges them adding up their values. This means after the function finishes the array should look like this:

  $items=array(
    0=>array('name'=>'red','value'=>5),
    1=>array('name'=>'black','value'=>1)
  );

('red' has two entries that have values 2 and 3, after the operation, red should have 1 entry with the value 5)

Thanks.

like image 919
chosta Avatar asked Nov 25 '25 17:11

chosta


1 Answers

First off, can you simply make it an associative array so that it handles itself for you?

$items = array(
    'red' => 5,
    'black' => 1,
);

If not, you could always do it by copying the array in a loop (not the best, but it works every time):

$newItems = array();
foreach ($items as $item) {
    if (!isset($newItems[$item['name']])) {
        $newItems[$item['name']] = $item;
    } else {
        $newItems[$item['name']]['value'] += $item['value'];
    }
}
$items = array_values($newItems);
like image 168
ircmaxell Avatar answered Nov 28 '25 08:11

ircmaxell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!