Need a simple solution to a PHP array problem?

Actually, I’m very ashamed to ask such a question, but on one of these days you spend 10 thousand hours on the simplest functions, and the more you try to solve their more complex solution that you will get ... I do not want to spend more time, therefore 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 identical names and combines them by adding their values. This means that 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 a value of 5)

Thank.

+3
source share
3

-, , ?

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

, , ( , ):

$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);
+2

:

// create a asssociative array with the name as the key and adding the values
$newitems = array();

foreach($items as $item){
  $newitems[$item['name']] += $item['value']:
}
// unset the original array by reinitializing it as an empty array
$items = array():
// convert the newitems array the the old structure
foreach($newitems as $key => $item){
  $items[] = array('name' => $key, 'value' => $item):
}
+2

Something like this should be about as good as it gets:

$map = array();
foreach ($items as $i => $item)
{
  if (!array_key_exists($item['name'], $map))
    $map[$item['name']] = $i;
  else
  {
    $items[$map[$item['name']]]['value'] += $item['value'];
    unset($items[$i]);
  }
}

Note that this modifies the original array $items.

+2
source

Source: https://habr.com/ru/post/1761359/


All Articles