2016-02-28 137 views
0

我有2個數組,你會看到下面的,我想把主題合併成一個。前兩個數組有一個和一個月的子數組。結果數組(3rd)必須具有相同月份的前兩個數組的總和。如何將2個數組合併成一個數組?

array:3 [ 
    0 => array:2 [ 
    "sum" => 179.0 
    "month" => "2016-01" 
    ] 
    1 => array:2 [ 
    "sum" => 34.0 
    "month" => "2016-02" 
    ] 
    2 => array:2 [ 
    "sum" => 67.0 
    "month" => "2016-03" 
    ] 
] 


array:2 [ 
    0 => array:2 [ 
    "sum" => 143.25 
    "month" => "2016-01" 
    ] 
    1 => array:2 [ 
    "sum" => 479.0 
    "month" => "2016-03" 
    ] 
] 


Total: 

array:3 [ 
    0 => array:3 [ 
    "sum" => 313.25 
    "month" => "2016-01" 
    ] 
    1 => array:2 [ 
    "sum" => 34.0 
    "month" => "2016-02" 
    ] 
    2 => array:2 [ 
    "sum" => 546.0 
    "month" => "2016-03" 
    ] 
] 

我的嘗試:

for($i=0;$i<count($com1);$i++){ 
      for ($j=0; $j < count($com2); $j++) { 
       if($com1[$i]['month'] == $com2[$j]['month']){ 
        $total = $com1[$i]['sum']+$com2[$j]['sum'] 
       } 
      } 
     } 

但它並沒有給結果我想

我升技小白......我希望有人可以提供幫助。由於

回答

0

試試這個:

$com1 = [ 
    0 => [ 
    'sum' => 179.0, 
    'month' => '2016-01' 
    ], 
    1 => [ 
    'sum' => 34.0, 
    'month' => '2016-02' 
    ], 
    2 => [ 
    'sum' => 67.0, 
    'month' => '2016-03' 
    ] 
]; 

$com2 = [ 
    0 => [ 
    'sum' => 143.25, 
    'month' => '2016-01' 
    ], 
    1 => [ 
    'sum' => 479.0, 
    'month' => '2016-03' 
    ] 
]; 

$total = []; 
foreach ($com1 as $data) { 
    $total[$data['month']] = $data; 
} 

foreach ($com2 as $data) { 
    if (!isset($total[$data['month']])) { 
     $total[$data['month']] = [ 
      'sum' => 0, 
      'month' => $data['month'] 
     ]; 
    } 
    $total[$data['month']]['sum'] += $data['sum']; 
} 

print_r($total); 
+0

這裏是演示:http://ideone.com/jI5Yyw – brevis

+0

作品,感謝您的幫助! – Cosmin

+0

我不禁注意到,在這裏輸出數組是一個關聯數組,而在問題中請求了一個順序數組。 – trincot

0

這裏是產生非關聯數組(如在你在你的問題所示):

$month_idx = []; // helper to identify at which index a certain month is stored 
$result = []; 
foreach (array_merge($data1, $data2) as $idx => $row) { 
    $month = $row["month"]; 
    if (!isset($month_idx[$month])) { 
     $month_idx[$month] = count($result); 
     $result[] = $row; 
    } else { 
     $result[$month_idx[$month]]["sum"] += $row["sum"]; 
    } 
} 

var_export($result); 

當$ data1和$ DATA2爲:

$data1 = array (
    array(
     "sum" => 179.0, 
     "month" => "2016-01" 
    ), 
    array(
     "sum" => 34.0, 
     "month" => "2016-02" 
    ), 
    array(
     "sum" => 67.0, 
     "month" => "2016-03" 
    ) 
); 
$data2 = array (
    array(
     "sum" => 143.25, 
     "month" => "2016-01" 
    ), 
    array(
     "sum" => 479.0, 
     "month" => "2016-03" 
    ) 
); 

然後輸出是:

array (
    0 => 
    array (
    'sum' => 322.25, 
    'month' => '2016-01', 
), 
    1 => 
    array (
    'sum' => 34, 
    'month' => '2016-02', 
), 
    2 => 
    array (
    'sum' => 546, 
    'month' => '2016-03', 
), 
) 
相關問題