2014-10-06 2 views
0

에 배열 값을 추가 나는 배열은 다음과 같이 구성했다 :결합 및 PHP

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

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

은 기본적으로 내가 어디를 찾는 ​​방법을 알고 싶어

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

는 내가하고 싶은 것은 다음과 같다 각 부분 배열의 첫 번째 값이 일치하고 그에 따라 두 번째와 세 번째 값을 추가합니까? 이 같은

+0

이 코드는 어떤 코드를 사용합니까? – Dan

답변

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

0

처럼, 그 후 키를 제거 할 수 있습니다 확인하지 않았다 -

  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]; 
} 
0

여기 있습니다. 두 번째 배열을 $ a2로 만들고 요소를 추가하고 그 합을 누적합니다. 너의 가치에 그것을 시험했다 ok.

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