在PHP中组合和添加数组值


Combining and Adding Array Values in PHP

我有一个结构如下的数组:

Array
(
    [0] => Array
        (
            [0] => cmi.interactions.0.result
            [1] => 1
            [2] => 0
        )
    [1] => Array
        (
            [0] => cmi.interactions.0.result
            [1] => 0
            [2] => 1
        )
    [2] => Array
        (
            [0] => cmi.interactions.0.result
            [1] => 0
            [2] => 1
        )
    [3] => Array
        (
            [0] => cmi.interactions.1.result
            [1] => 1
            [2] => 0
        )
    [4] => Array
        (
            [0] => cmi.interactions.1.result
            [1] => 1
            [2] => 0
        )
    [5] => Array
        (
            [0] => cmi.interactions.1.result
            [1] => 1
            [2] => 0
        )
)

我想要的是以下内容:

Array
(
    [0] => Array
        (
            [0] => cmi.interactions.0.result
            [1] => 1
            [2] => 2
        )
    [1] => Array
        (
            [0] => cmi.interactions.1.result
            [1] => 3
            [2] => 0
        )
)

基本上,我想知道如何找到每个子数组中的第一个值匹配的地方,并相应地添加第二个和第三个值?

类似的事情,没有检查

$out = array();
foreach($arr as $el)
  if (!isset($out[$el[0]]))
     $out[$el[0]] = $el;
  else
     for($i = 1; $i < count($el); $i++)
        $out[$el[0]][$i] += $el[$i];

之后可以移除密钥,如$out = array_values($out);

对于这种情况,您可以使用以下算法:-

  1. 对数组进行排序
  2. 在数组上迭代,如果第0个元素发生了变化,请跟踪数组
  3. 将2个和保持在2个不同的变量中

下面是算法的提示。我没有测试它,所以,它可能无法完全工作。但这应该会给你一个继续前进的好提示

$prevValue="";
$sum1=0;
$sum2=0;
$index=0;
foreach ($arr as $value) {
    if($prevValue==$value[0])
    {
        if(value[1]==1)
            $sum1++;
        if(value[2]==1)
            $sum2++;
    }else{
        $ansArr[$index]=array($value[0], $sum1,$sum2);
    }
    $prevValue=$value[0];
}

开始吧。我们将第二个数组构建为$a2,并向其中添加元素,然后将总和累积到其中。根据您的值对其进行测试。好的。

function parse($a)
{
    $a2 = array();
    for ($i = 0; $i < sizeof($a); $i++) {
        $isFound = false;
        for ($i2 = 0; $i2 < sizeof($a2); $i2++) {
            if ($a[$i][0] == $a2[$i2][0]) {
                // We've already run into this search value before
                // So add the the elements
                $isFound = true;
                $a2[$i2][1] += $a[$i][1];
                $a2[$i2][2] += $a[$i][2];
                break;
            }
        }
        if (!$isFound) {
            // No matches yet
            // We need to add this one to the array
            $a2[] = $a[$i];
        }
    }
    return $a2;
}