阵列打印

时间:2012-08-10 05:47:55

标签: php arrays

$transactions = array (
array( 'SiteID' => 147, 'Amount' => '500.00', 'TransactionType' => 'Deposit' ),

array( 'SiteID' => 147, 'Amount' => '500.00', 'TransactionType' => 'Redemption'),

array( 'SiteID' => 147, 'Amount' => '1500.00', 'TransactionType' => 'Deposit' ),

array( 'SiteID' => 147, 'Amount' => '200.00', 'TransactionType' => 'Reload' ),

array( 'SiteID' => 150, 'Amount' => '100.00', 'TransactionType' => 'Deposit' ),

array( 'SiteID' => 3,   'Amount' => '500.00', 'TransactionType' => 'Redemption' ),

array( 'SiteID' => 150, 'Amount' => '200.00', 'TransactionType' => 'Redemption' ),

array( 'SiteID' => 3,   'Amount' => '500.00', 'TransactionType' => 'Deposit' ),

array( 'SiteID' => 3,   'Amount' => '200.00', 'TransactionType' => 'Deposit' ),

array( 'SiteID' => 3,   'Amount' => '200.00', 'TransactionType' => 'Reload' ),

array( 'SiteID' =>147, 'Amount' => '500.00', 'TransactionType' => 'Redemption' )
);

$totals = null;

foreach ($transactions as $t){

$amount = (float) $t['Amount'];

if (isset($totals[ $t['SiteID'] ][ $t['TransactionType'] ])){
    $totals[ $t['SiteID'] ][ $t['TransactionType'] ] += (float) $amount;
} else {
    $totals[ $t['SiteID'] ][ $t['TransactionType'] ] = (float) $amount;
}
}

print_r ($totals);

这是代码,但打印如下:

Array ( [147] => Array ( [D] => 455500 [W] => 460216.4 [R] => 158000 ) 

[145] => Array ( [D] => 85500 [W] => 78763.75 [R] => 14500 )

[146] => Array ( [D] => 64200 [W] => 91121.94 [R] => 42800 )

我需要print_r这样的结果:

Array ( [147] => Array ( [Deposit] => 455500 [Redemption] => 460216.4 [Reload] => 158000 ) 

[145] => Array ( [Deposit] => 85500 [Redemption] => 78763.75 [Reload] => 14500 )

[146] => Array ( [Deposit] => 64200 [Redemption] => 91121.94 [Reload] => 42800 )

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

谢谢,请回复。

2 个答案:

答案 0 :(得分:0)

使用

$result=array();
foreach($total as $key=>$value)
{
    $result=array_merge($result,array($key=>array("Deposit"=>$value['D'],"Redemption"=>$value['W'],"Reload"=>$value['R'])));
}
print_r($result);

答案 1 :(得分:0)

TRY

foreach ($transactions as $k=>$t){

$amount = (float) $t['Amount'];

if (isset($totals[ $t['SiteID'] ][ $t['TransactionType'] ])){
    $totals[ $t['SiteID'] ][ $t['TransactionType'] ] += (float) $amount;
} else {
    $totals[ $t['SiteID'] ][ $t['TransactionType'] ] = (float) $amount;
}
}