【问题标题】:A simple solution to a PHP array problem is needed?需要一个简单的 PHP 数组问题解决方案吗?
【发布时间】:2011-04-03 07:27:35
【问题描述】:

实际上我很尴尬地问这样一个问题,但在那些日子里,你会在最简单的功能上花费 10000 小时,而且你尝试解决的次数越多,得到的解决方案就越复杂......我不想浪费更多时间,所以这就是问题所在。

我有一个数组:

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

我需要一个函数来检测相同的名称并将它们合并起来,并将它们的值相加。这意味着函数完成后,数组应如下所示:

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

('red'有两个值为2和3的条目,操作后red应该有1个值为5的条目)

谢谢。

【问题讨论】:

    标签: php arrays function merge


    【解决方案1】:

    首先,您能否简单地将其设为关联数组,以便它为您处理自己?

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

    【讨论】:

    • 嗯,这是我想到的第一个解决方案,但我没有像比石头更聪明的人那样使用“!isset”,而是决定找到 if “count($newItems)> 0" ,这当然不是正确的方法,但延续几乎与此相似。无论如何,谢谢...它有效...
    • 好吧,clever 一点。 Debugging is twice as hard as writing the code in the first place. Therefore if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.。所以不要太沉迷于代码的“聪明”或“美丽”……首先选择可行的,并且可以维护的东西……
    • 你说得对,我通常会尝试让事情发挥作用,然后我会尝试让它们工作得更快(聪明)。在这种情况下,我只是陷入了自己的想法,忘记了我实际上可以使用 array_values() 将数组转换回来。这只是你需要的那些日子之一......无论如何,谢谢......祝你有美好的一天。
    【解决方案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):
    }
    

    【讨论】:

    • 一个小问题。请始终初始化您的变量。所以你unset($items)。然后你需要一个$items = array();(在这种情况下它本身就足够了)......
    • 对不起,通常是这样。这个我忘记了。将编辑我的答案。
    【解决方案3】:

    这样的东西应该尽可能好:

    $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]);
      }
    }
    

    请注意,这会修改原始的 $items 数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-07
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多