在PHP中,在多维数组中查找重复条目,然后对该数组的特定键中的值求和

时间:2011-04-28 16:32:28

标签: php

我有一个从CSV文件创建的数组。该数组包含以下内容。基本上它有四行六列。 I.E.它是多维的。

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,所以任何帮助将不胜感激。我已经找到了一个列的夏季工作,但是我无法想出要搜索数组中的“匹配”键,然后通过求和将它们组合在一起。

提前致谢!

2 个答案:

答案 0 :(得分:1)

我会遍历每个数组并

  1. 创建一个可能包含10个字符的数组
  2. 如果找到匹配项,则将其余列添加到该匹配项
  3. 这假设可以有多个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
    )
    

答案 1 :(得分: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...
}