2013-03-28 87 views
1

我已經嘗試過20種不同的想法,我想我已經走了這麼多圈,我不記得我開始的地方。我相信這也是一個簡單的例子。我有一個數組;我有數組;PHP:基於特定鍵值的數組合並元素

Array 
(
    [0] => Array 
     (
      [employee] => 15 
      [first_name] => Person1 
      [surname] => Person1 
      [totaltime] => 183.75 
      [type] => 0 

     ) 

    [1] => Array 
     (
      [employee] => 15 
      [first_name] => Person1 
      [surname] => Person1 
      [totaltime] => 64.50 
      [type] => 1    
     ) 

    [2] => Array 
     (
      [employee] => 23 
      [first_name] => Person2 
      [surname] => Person2 
      [totaltime] => 2.00 
      [type] => 0 
     ) 

    [3] => Array 
     (
      [employee] => 51 
      [first_name] => Person3 
      [surname] => Person3 
      [totaltime] => 119.25 
      [type] => 0    
     ) 

    [4] => Array 
     (
      [employee] => 59 
      [first_name] => Person4 
      [surname] => Person4 
      [totaltime] => 170.75 
      [type] => 0 
     ) 
) 

我需要合併在employee數量是相同的元素,並添加totaltime元素基礎上,type新的密鑰。這就是我的意思。

Array 
(
    [0] => Array 
     (
      [employee] => 15 
      [first_name] => Person1 
      [surname] => Person1 
      [totaltime_type_0] => 183.75 
      [totaltime_type_1] => 64.50 

     )  

    [1] => Array 
     (
      [employee] => 23 
      [first_name] => Person2 
      [surname] => Person2 
      [totaltime_type_0] => 2.00 
      [totaltime_type_1] => 0 
     ) 

    [2] => Array 
     (
      [employee] => 51 
      [first_name] => Person3 
      [surname] => Person3 
      [totaltime_type_0] => 119.25 
      [totaltime_type_1] => 0    
     ) 

    [3] => Array 
     (
      [employee] => 59 
      [first_name] => Person4 
      [surname] => Person4 
      [totaltime_type_0] => 170.75 
      [totaltime_type_1] => 0 
     ) 
) 

我可以在查詢級別執行此操作,但創建原始數組的SQL非常複雜,我寧願只維護它的一個版本。

任何有關最佳方法的建議都會幫助我重新走上正軌。並將真正感激。

回答

3

試試這個:

$res  = array(); 
foreach($your_array as $val){ 
    $res[$val['employee']]['employee']   = $val['employee']; 
    $res[$val['employee']]['first_name']  = $val['first_name']; 
    $res[$val['employee']]['surname']   = $val['surname']; 
    if($val['type'] == 0){ 
     if(array_key_exists("totaltime_type_0",$res[$val['employee']])){ 
     $res[$val['employee']]['totaltime_type_0'] += $val['totaltime']; 
     } 
     else{ 
     $res[$val['employee']]['totaltime_type_0'] = $val['totaltime']; 
     } 
    } 
    if($val['type'] == 1){ 
     if(array_key_exists("totaltime_type_1",$res[$val['employee']])){ 
     $res[$val['employee']]['totaltime_type_1'] += $val['totaltime']; 
     } 
     else{ 
     $res[$val['employee']]['totaltime_type_1'] = $val['totaltime']; 
     } 
    } 
} 

echo "<pre>"; 
print_r(array_values($res)); 
+0

這是一個超快速的答案,並可以正常使用!謝謝。我欠你一個;-) – shanem 2013-03-28 10:32:26

+0

@shanem:謝謝:) – 2013-03-28 10:33:13