如何总结数组值?

时间:2012-08-09 08:49:13

标签: php arrays

为清楚起见,这是输入的数据:

阵 (     [0] =>排列         (             [SiteID] => 147             [金额] => 500.00             [TransactionType] => d         )

[1] => Array
    (
        [SiteID] => 145
        [Amount] => 500.00
        [TransactionType] => D
    )

[2] => Array
    (
        [SiteID] => 145
        [Amount] => 500.00
        [TransactionType] => D
    )

[3] => Array
    (
        [SiteID] => 147
        [Amount] => 500.00
        [TransactionType] => D
    )

[4] => Array
    (
        [SiteID] => 146
        [Amount] => 500.00
        [TransactionType] => D
    )
[5] => Array
    (
        [SiteID] => 146
        [Amount] => 500.00
        [TransactionType] => D
    )
[6] => Array
    (
        [SiteID] => 145
        [Amount] => 500.00
        [TransactionType] => W
    )

[7] => Array
    (
        [SiteID] => 145
        [Amount] => 500.00
        [TransactionType] => W
    )

[8] => Array
    (
        [SiteID] => 146
        [Amount] => 330.00
        [TransactionType] => W
    )

[9] => Array
    (
        [SiteID] => 146
        [Amount] => 500.00
        [TransactionType] => W
    )

[10] => Array
    (
        [SiteID] => 3
        [Amount] => 500.00
        [TransactionType] => D
    )

我需要获得所有事务的总和相同的SiteID和它的TransactionType。例如:

D - 存款,W - 赎回,R - 重新加载

结果:array ([147]=>array([Deposit] => 1000, [Reload]=>3000, [Redemption]=>2000))

注意:147是SiteID。

我需要计算相同SiteID的所有交易的存款,重新加载,赎回。

如果SiteID不止一次存在,只需在每个周期添加存款,重新加载和赎回。 :)

请回复。谢谢,并以适当的方式指导我!!

2 个答案:

答案 0 :(得分:0)

试试这个

<?php
$array=array ("SiteID"=>array("Deposit" => 1000, "Reload"=>3000, "Redemption"=>2000));
$val=0;
foreach($array["SiteID"] as $key=>$value){
$val=$val+$value;
}
echo $val;
?>

答案 1 :(得分:0)

$values = array(
    'Deposit' => 0,
    'Reload'       => 0,
    'Redemption' => 0
);
foreach ($array as $item) {
    $values[$item['SiteID']] += array_sum($item['SiteID']);
}
print_r($values);