折叠在2D数组中添加第二个的唯一值

时间:2012-06-28 13:49:37

标签: php arrays

我有一个循环,它将两个值的数组添加到主数组中。

如何合并主阵列中具有相同第一个值的所有数组,同时将第二个值相加?

$mainData = array() ;
//Loop...

$cRes = $dbh->query("SELECT overdue FROM _credit_control_overdue WHERE entityID = $entityId") ;
        $currentOwed = $cRes->fetchColumn() ;
        $dbh->exec("REPLACE INTO _credit_control_overdue (entityID, overdue) VALUES ('$entityId', '$remaining')") ;
        $totalRemaining += $remaining ;

        array_push($mainData, array($entityId, $remaining)) ;
//End of loop

在许多情况下,$ entityId将是相同的,而剩余的$将是不同的。

现在我需要一个类似于array_unique的函数,它会给我一个唯一的$ entityId,但是剩下的所有$剩余值都被添加了,所以我留下了例如2339,83572.60。

希望我已经清楚地解释了这一点!


这是我想要的输出:

数组([0] =>数组([0] => 2499 [1] => 5314.50)[1] =>数组([0] => 639 [1] => 75.00 ))

即Array([0] => UNIQUEID [1] => SUM)

1 个答案:

答案 0 :(得分:0)

执行此操作的最佳方法可能是首先使用$ entityId作为键构建一个关联数组(哈希)(这将为每个键提供一个唯一的条目)以及剩余的累计总数作为值:

// Initialise the hash before looping
$perEntityTotals = array();

/* Loop ... */

// Add the $remaining value to the appropriate entity's total
// If the key doesn't yet exist, it will be created with the value $remaining
$perEntityTotals[$entityId] += $remaining;

/* End Loop */

要按照您最初的要求重新格式化,您需要操作哈希:

$mainData = array();
foreach ( $perEntityTotals as $entityId => $total )
{
    $mainData[] = array($entityId, $total);
}

以下内容相同,但有些难以阅读:

$mainData = array_map(
    NULL,             // see Example #4 on http://php.net/array_merge
    array_keys($perEntityTotals),
    array_values($perEntityTotals) 
);