2014-02-09 55 views
0

陣列我有兩個數組像下面金額和合並在php

Array 
(
    [0] => Array 
     (
      [taskcount] => 3 
      [client_id] => 1 
      [client_name] => No Project Set 
     ) 

    [1] => Array 
     (
      [taskcount] => 1 
      [client_id] => 4 
      [client_name] => Check 
     ) 

    [2] => Array 
     (
      [taskcount] => 1 
      [client_id] => 5 
      [client_name] => Others 
     ) 

) 

Array 
    (
     [0] => Array 
      (
       [taskcount] => 1 
       [client_id] => 5 
       [client_name] => Others 
      ), 
     [1] => Array 
      (
       [taskcount] => 1 
       [client_id] =>7 
       [client_name] => Othersnew 
      ) 

    ) 

,我想合併兩個數組,以返回一些東西一樣,意味着我要總結taskcount如果兩個數組都有共同點client_id

Array 
    (
     [0] => Array 
      (
       [taskcount] => 3 
       [client_id] => 1 
       [client_name] => No Project Set 
      ) 

     [1] => Array 
      (
       [taskcount] => 1 
       [client_id] => 4 
       [client_name] => Check 
      ) 

     [2] => Array 
      (
       [taskcount] => 2 
       [client_id] => 5 
       [client_name] => Others 
      ) 
     [3] => Array 
      (
       [taskcount] => 1 
       [client_id] =>7 
       [client_name] => Othersnew 
      ) 


    ) 
+0

聽起來像一個有趣的遞歸問題,這將會是很高興看到你的第一次嘗試。對不起,強制性的*看到你的第一次嘗試,除了你想要的結果 – Bryan

+0

你必須結合使用'array_uintersect()'(http://www.php.net/manual/en/function.array-uintersect.php)用'array_merge()'。 – hindmost

回答

1

這工作(雖然是困難的方式) -

function merge_n_add($a1, $a2){ 
    $result = $a1; 
    $client_ids = array_map(function($a){return $a['client_id'];}, $result); 
    foreach($a2 as $v){ 
     if(in_array($v['client_id'], $client_ids)){ 
      $res_index = array_search($v['client_id'] ,$client_ids); 
      $result[$res_index]['taskcount'] += $v['taskcount']; 
     }else{ 
      $result[] = $v; 
     } 
    } 
    return $result; 
} 
//Assuming the 2 arrays are $a1 and $a2 
var_dump(merge_n_add($a1, $a2)); 

這是給定的輸入輸出 -

/* 
    OUTPUT 
*/ 
array 
    0 => 
    array 
     'taskcount' => int 3 
     'client_id' => int 1 
     'client_name' => string 'No Project Set' (length=14) 
    1 => 
    array 
     'taskcount' => int 1 
     'client_id' => int 4 
     'client_name' => string 'Check' (length=5) 
    2 => 
    array 
     'taskcount' => int 2 
     'client_id' => int 5 
     'client_name' => string 'Others' (length=6) 
    3 => 
    array 
     'taskcount' => int 1 
     'client_id' => int 7 
     'client_name' => string 'Othersnew' (length=9) 
0

將它們命名爲$ Array1,$ Array2。

一次將一個客戶端從$ Array2添加到$ Array1。

檢查是否有相同的客戶端求和,否則添加新的。

while (count($Array2) !== 0) { 
    $anotherClient = $array_pop($Array2); 
    foreach($Array1 as $client) { 
     if ($anotherClient['client_id'] === $client['client_id']) { 
      $client['taskcount'] += $anotherClient['taskcount']; 
      continue; 
     } 
    } 
    array_push($Array1, $anotherClient); 
}