2016-06-07 5 views
1

소스와 타겟이 같은 모든 엔트리에 대해 total_volume을 요약하고자하는 다음 배열이 있습니다. 기존의 배열을PHP는 두 개의 키가 동일한 값을 갖는 배열 엔트리를 합산합니다.

ResultArray (
[0] => Array 
    (
     [source] => ABC 
     [target] => DEF 
     [total_volume] => 15 
    ) 

[1] => Array 
    (
     [source] => ABC 
     [target] => GHI 
     [total_volume] => 5 
    ) 
) 

내 제 생각 llop하는 것 및 매칭 소스 - 인 항목 여부 ResultArray 위에 중첩 루프를 통해 확인 :

Array (
[0] => Array 
    (
     [source] => ABC 
     [target] => DEF 
     [total_volume] => 10 
    ) 

[1] => Array 
    (
     [source] => ABC 
     [target] => GHI 
     [total_volume] => 5 
    ) 
[2] => Array 
    (
     [source] => ABC 
     [target] => DEF 
     [total_volume] => 5 
    ) 
) 

얻어진 배열은 다음과 같아야 대상 쌍이 이미 있습니다.

array_walk() 또는 이와 유사한 방법을 사용하는 다른 방법이 있습니까?

미리 도움 주셔서 감사합니다.

+0

원시 코드를 사용하여 만들 수 있습니다. 정확히 'array_walk' 또는 원시가 필요합니까? –

+0

이 문제를 해결하는 방법을 알지 못해서 나는 모든 솔루션에 만족할 것입니다. 그래서 원시 작품은 나를 위해 잘 작동합니다. 미리 감사드립니다. – mxzwrnz

+0

[키 PHP 배열에 대해 동일한 값을 갖는 값의 합계 가져 오기] 가능한 중복 (http://stackoverflow.com/questions/37654630/get-sum-of-values-which-have-same-value-for-key -php-array) –

답변

2

꽤 있지만를 heres 나는 중첩 된 foreach는 함께 할 것입니다 어떻게하지;

$aStartingArray = array(); 
$aStartingArray[] = array('source'=>'ABC', 'target' => 'DEF', 'total_volume' => 10); 
$aStartingArray[] = array('source'=>'ABC', 'target' => 'GHI', 'total_volume' => 5); 
$aStartingArray[] = array('source'=>'ABC', 'target' => 'DEF', 'total_volume' => 5); 


$aSortedArray = array(); 

foreach ($aStartingArray as $aArray) { 

    $bSet = false; 

    foreach ($aSortedArray as $iPos => $aTempSortedArray) { 

     if(
      $aTempSortedArray['source'] == $aArray['source'] && 
      $aTempSortedArray['target'] == $aArray['target']){ 

      $aSortedArray[$iPos]['total_volume'] += $aArray['total_volume']; 

      $bSet = true; 
     } 

    } 

    if(!$bSet) { 

     $aSortedArray[] = array(
      'source' => $aArray['source'], 
      'target' => $aArray['target'], 
      'total_volume' => $aArray['total_volume'] 
      ); 
    } 
} 


var_dump($aSortedArray); 
1

이 빠른 시도입니다 (죄송합니다, 그것은 두 번 array_walk 사용합니다)

<?php 

$a = [ 
    ['source' => 'ABC', 'target' => 'DEF', 'total_volume' => 10 ], 
    ['source' => 'ABC', 'target' => 'GHI', 'total_volume' => 5 ], 
    ['source' => 'ABC', 'target' => 'DEF', 'total_volume' => 5 ], 
]; 

$tmp = []; 

array_walk($a, function (&$item, $key) use (&$tmp) { 
    $resKey = $item['source'].'_'.$item['target']; 
    if (!isset($result[$resKey])) { 
     $result[$resKey] = 0; 
    } 
    $tmp[$resKey] += $item['total_volume']; 
}); 

$result = []; 
array_walk($tmp, function (&$item, $key) use (&$result) { 
    list ($source, $target) = explode('_', $key); 
    $result[] = ['source' => $source, 'target' => $target, 'total_volume' => $item]; 
}); 

var_dump($result); 
+0

또한 답변을 시도했지만 완료하지 않았습니다. 좋은 답변입니다. –

1

어때? 내 생각에 조금 간략히.

$a = [ 
    ['source' => 'ABC', 'target' => 'DEF', 'total_volume' => 10 ], 
    ['source' => 'ABC', 'target' => 'GHI', 'total_volume' => 5 ], 
    ['source' => 'ABC', 'target' => 'DEF', 'total_volume' => 5 ], 
]; 
$result = $result2 = []; 
array_walk($a, function(&$item, $key) use(&$result) { 
    if(! isset($result[$item['source']])) 
     $result[$item['source']] = []; 
    if(! isset($result[$item['source']][$item['target']])) 
     $result[$item['source']][$item['target']] = 0; 
    $result[$item['source']][$item['target']] += $item['total_volume']; 
}); 
foreach($result as $key => $val) { 
    foreach($val as $k => $v) { 
     $result2[] = [$key,$k,$v]; 
    } 
} 
print_r($result2); 
0

또 다른 대안입니다. 최고는 아니지만 작동합니다.

$arr = [ 
    ['source' => 'ABC', 'target' => 'DEF', 'total_volume' => 10 ], 
    ['source' => 'ABC', 'target' => 'GHI', 'total_volume' => 5 ], 
    ['source' => 'ABC', 'target' => 'DEF', 'total_volume' => 5 ], 
]; 

$res = $resulrArr = []; 
foreach($arr as $record){ 
    $record = array_values($record); 
    $res[$record[0].'_'.$record[1]] = !empty($res[$record[0].'_'.$record[1]]) ? $res[$record[0].'_'.$record[1]] + $record[2] : $record[2]; 
} 

$resulrArr = array_map(function($v,$k){ 
    $data = explode('_',$k); 
    $resulrArr['source'] = $data[0]; 
    $resulrArr['target'] = $data[1]; 
    $resulrArr['total_volume'] = $v; 
    return $resulrArr; 
},$res,array_keys($res)); 

echo '<pre>'; print_r($resulrArr); 
관련 문제