2014-10-06 28 views
0

添加數組值我有一個數組結構是這樣的:合併和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 
     ) 
) 

基本上我想知道如何找到其中每個子陣列中的第一個值是否匹配並相應地添加第二個和第三個值?

+0

看起來很可行,你有什麼代碼試圖做到這一點? – Dan 2014-10-06 17:43:06

回答

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

+0

這工作,謝謝你! – hsmith 2014-10-06 17:56:55

0

對於這種情況,你可以使用下面的算法: -

  1. 對陣列進行排序
  2. 遍歷數組,並在第0個元素髮生更改時跟蹤數組。
  3. 保持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]; 
} 
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; 
}