2011-10-12 82 views
0

我有兩個PHP數組。一個包含一個組名,另一個包含工資薪水值。如果一個PHP數組中存在值,請將值添加到第二個數組中

$group_wages_array = Array ([0] => 1 [1] => 4 [2] => 1 [3] => 3); 

這意味着有四名員工按計劃進行工作。兩個被分配給組1,另一個組4和最後組3

第二陣列如下:

$tot_wages_array = Array ([0] => 500 [1] => 44 [2] => 80 [3] => 11.25); 

這是每個員工的工資的樣本陣列。這兩個數組都是按順序構造的,因爲值會在mysql while循環中添加,因爲它會從數據庫中提取信息。


後來就下了線,我結合了兩個數組,以獲得一個數組,其中的關鍵是組號和值是該組的工資總額:

$combined_group_wages = array_combine($group_wages_array, $tot_wages_array); 

這很像除了一個以上的員工被分配到同一組時,還可以享受魅力。這些陣列是建立在一個MySQL while循環,它遍歷每個員工的信息:

array_push($tot_wages_array, $totemp_wages_sch); // Add their wage to the array 
array_push($group_wages_array, $emp_data['group_id']); // Add their group to the array 

而不是僅僅將數據推到數組,我需要做到這一點...我知道英語,但是我不」 t知道如何編碼它:

如果$ emp_data ['group_id']作爲$ group_wages_array中的值存在,則不會向該數組添加任何內容,而是獲取該密鑰。 $ totemp_wages_sch添加到$ tot_wages_array其中key = group_wages_array關鍵

我知道這聽起來更像是一個SQL查詢,但我必須保持鍵和值,以使他們能夠在後面的頁面合併。如果我可以得到這個工作的權利,在這個例子中顯示的陣列將是:

$group_wages_array = Array ([0] => 1 [1] => 4 [2] => 3); 
$tot_wages_array = Array ([0] => 580 [1] => 44 [2] => 11.25); 

$combined_group_wages = array_combine($group_wages_array, $tot_wages_array); 

$combined_group_wages = Array ([1] => 580 [4] => 44 [3] => 11.25); 

...我必須使這個工作使用PHP。有任何想法嗎?


我想出了基於兩個提交以下問題的答案組合的解決方案。在這裏,它是如果它可以幫助某人:

 if(in_array($emp_data['group_id'], $group_wages_array)){ 
     $key = key($group_wages_array); 
     $tot_wages_array[$key] += $totemp_wages_sch; 

     } else { 

     array_push($group_wages_array, $emp_data['group_id']);  
     array_push($tot_wages_array, $totemp_wages_sch); 
     } 
+0

在你上一個示例代碼塊中,顯示你想要的'$ combined_group_wages'數組。 – webbiedave

+0

已更新,顯示新的組合陣列。 – Oseer

+0

我建議你處理對象,而不是這些數組抽象。我會查看你的代碼並嘗試提供幫助,但這實際上是我建議給你的。 –

回答

2

這應做到:

$group_wages_array = array(1, 4, 1, 3); 
$tot_wages_array = array(500, 44, 80, 11.25); 

$combined_group_wages = array(); 

for ($i=0; $i<count($group_wages_array); $i++) { 
    $group = $group_wages_array[$i]; 
    if (array_key_exists($group_wages_array[$group], $combined_group_wages)) { 
     $combined_group_wages[$group] += $tot_wages_array[$i]; 
    } else { 
     $combined_group_wages[$group] = $tot_wages_array[$i]; 
    } 

} 

print_r($combined_group_wages); 

產量:

Array 
(
    [1] => 580 
    [4] => 44 
    [3] => 11.25 
) 

但我建議你只需切換到使用對象來更好地表示數據。

+0

男人看起來不錯,但當我'print_r($ combined_group_wages)'所有我得到的是數組() – Oseer

+0

@ user971230這是我運行我的測試的確切代碼。當您複製或實施它時,您一定做錯了什麼。 –

+0

我想出了一個基於你的代碼和上面的prestig3的組合的解決方案。我現在發佈它。感謝您的幫助! – Oseer

1

如果我能看到整個代碼將幫助很多,但這裏是你的英文轉換爲PHP。給我更多的代碼,我可以完善它,直到那就試試這個 - >

if(in_array($emp_data['group_id'], $group_wages_array)){ 
    $key = key($group_wages_array); 
    $tot_wages_array[$key] = $totemp_wages_sch; 
} else { 
    array_push($group_wages_array, $emp_data['group_id']); 
} 
+1

是的我同意更多的信息幫助。另外至少有一半是SQL,並且可以立即在while循環內部構建一個單獨的(多維數據)數組!發表一張表的描述會對此有所幫助。 – Melsi

相關問題