开发者

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'=&g开发者_开发百科t;'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.


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);


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 $items array.


That should do the job:

// 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):
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜