2011-04-28 11 views
2

我有一個從CSV文件創建的數組。該數組包含以下內容。基本上它有四行六列。 I.E.它是多維的。在PHP中找到多維數組中的重複條目,然後對該數組中的特定鍵值進行求和

Array ( 
    [1] => Array ( 
     [WBS Element] => 1234567.01 
     [Proj System Status] => 
     [CY Actuals] => 579373 
     [ITD Actuals] => 696,609 
     [Overall Commitment] => 
     [Overall Assigned] => 696,609 
     [CYSpent] => 579,373) 
    [2] => Array ( 
     [WBS Element] => 1234567.02 
     [Proj System Status] => 
     [CY Actuals] => 86689 
     [ITD Actuals] => 86,689 
     [Overall Commitment] => 
     [Overall Assigned] => 86,689 
     [CYSpent] => 86,689) 
    [3] => Array ( 
     [WBS Element] => 1234567.02.01 
     [Proj System Status] => 
     [CY Actuals] => 10750 
     [ITD Actuals] => 86,689 
     [Overall Commitment] => 
     [Overall Assigned] => 86,689 
     [CYSpent] => 86,689) 
    [4] => Array ( 
     [WBS Element] => 1234567.02.02 
     [Proj System Status] => 
     [CY Actuals] => 22756 
     [ITD Actuals] => 86,689 
     [Overall Commitment] => 
     [Overall Assigned] => 86,689 
     [CYSpent] => 86,689) 
    ) 

您會注意到我的一個鍵「WBS Element」中有一個值,其中前十個字符可能與數組中的另一行匹配。我需要做的是取「WBS元素」的前十個字符所匹配的任何行並將其他列合併在一起,以便結果爲具有相同列的聚合數組,但前十個字符沒有匹配的行。

希望這是有道理的,我正在努力完成。當談到PHP時,我是新的,所以任何幫助將不勝感激。我希望得到一個列summerization工作,但我不能找出一個數組搜索「匹配」的鍵,然後通過求和結合起來。

提前致謝!

+0

輸出@ user729691:它總是幫助,如果你真的發表了預期的結果的一個例子。 – netcoder 2011-04-28 16:37:21

+0

好點,下次我會做:-)再次感謝您的幫助! – danielmesh 2011-04-28 20:08:30

回答

1
$new_array = array(); 
foreach ($array as $row) 
{ 
    $key = substr($row['WBS Element'],0,10); 

    $new_array[$key]['WBS Element'] = $key; // optional 
    $new_array[$key]['Proj System Status'] += $row['Proj System Status']; 
    $new_array[$key]['CY Actuals'] += $row['CY Actuals']; 
    $new_array[$key]['ITD Actuals'] += $row['ITD Actuals']; 
    // same for Overall Commitment, etc... 
} 
+0

非常感謝!看起來它現在工作得很好,我很欣賞代碼。 – danielmesh 2011-05-02 20:38:17

1

我將循環遍歷每個陣列和

  1. 創建可能10個字符匹配的數組
  2. 如果發現匹配,列的其餘部分添加到該匹配

這假設可以有多個可匹配的10個字符的字符串:

$stats = <your array from above> 
$output = array(); 

foreach($stats as $stat){ 
    // first we create an element in the array so we can sum 
    $key = substr($stat['WBS Element'], 0, 10); 
    if (!array_key_exists($stat['WBS Element'], $output)){ 
     $output[$key] = array(); 
    } 

    // sum up rest of columns based on $output[$key] 
    // or simply create them if the if-statement was matched above 
    $output[$key]['CYSpent'] += $stat['CYSpent']; 
    // etc 
} 

這會給你的

array(
    [10-char-key-1] => array(
     // columns 
    ) 
    [10-char-key-2] => array(
     // columns 
    ) 
    // etc 
) 
+0

非常感謝quik回覆,它非常棒!我只是無法弄清楚現在如何總結這一列。我正在使用的欄是「CY Actuals」。如果您需要更多信息,請告知我們:-)再次感謝您的幫助,這真是太棒了!我很喜歡PHP – danielmesh 2011-04-28 20:00:21

+0

用上面的代碼和「CY Actuals」的$輸出鍵,我得到以下結果。 陣列([1234567.01] =>數組([CY實際值] => 579373)[1234567.02] =>數組([CY實際值] => 22756)) 我需要得到這樣的結果: 陣列([1234567.01 ] => Array([CY Actuals] => 579373)[1234567.02] => Array([CY Actuals] => 120195)) – danielmesh 2011-04-28 20:06:17

相關問題