2016-11-17 57 views
0

我有以下的數組:PHP ARRAY - 結合還是分組?

Array 
(
    [0] => Array 
     (
      [0] => Monday 
      [1] => 0 
      [2] => 1 
     ) 

    [1] => Array 
     (
      [0] => Friday 
      [1] => 4717 
      [2] => 1 
     ) 

    [2] => Array 
     (
      [0] => Friday 
      [1] => 2074 
      [2] => 1 
     ) 

    [3] => Array 
     (
      [0] => Thursday 
      [1] => 1520 
      [2] => 1 
     ) 

) 

我想重複的天結合在一起,同時還加入2個值([1] + [1]和[2] + [2])一起使用。

例如,星期五是重複的,從而它會返回: [0] =>星期五 [1] => 6791 [2] => 2

任何想法?

回答

0

迭代數組,使用day作爲鍵將值添加到另一個數組($combined)。

$array = [ [ 'Monday',  0, 1 ], 
      [ 'Friday', 4717, 1 ], 
      [ 'Friday', 2074, 1 ], 
      [ 'Thursday', 1520, 1 ] ]; 

$combined = []; 

foreach ($array as $value) { 
    $day = $value[0]; 
    if (!array_key_exists($day, $combined)) { 
     # Does not exist, create in resulting array 
     $combined[$day] = $value; 
    } 
    else { 
     # Exists - add to values 
     $combined[$day][1] += $value[1]; 
     $combined[$day][2] += $value[2]; 
    } 
} 
print_r(array_values($combined)); 

輸出:

Array 
(
    [0] => Array 
     (
      [0] => Monday 
      [1] => 0 
      [2] => 1 
     ) 

    [1] => Array 
     (
      [0] => Friday 
      [1] => 6791 
      [2] => 2 
     ) 

    [2] => Array 
     (
      [0] => Thursday 
      [1] => 1520 
      [2] => 1 
     ) 
) 
0

這樣的事情應該工作。

$sorted = array(); 

foreach ($days as $day) { 
    $sorted[ $day[0] ][ 0 ] = $day [ 0 ]; 
    $sorted[ $day[0] ][ 1 ] += $day [ 1 ]; 
    $sorted[ $day[0] ][ 2 ] += $day [ 2 ]; 
} 

$days = $sorted; 

print_r($days); 

如果您需要回密鑰,只需再次對它們進行排序。

$sorted = array(); 

foreach ($days as $day) { 
    $sorted[] = $day; 
} 

$days = $sorted;