使用PHP在mongodb中的数组总和

时间:2012-06-08 13:24:38

标签: php mongodb

PHP中的mongo db中的数组总和

[_id] => MongoId Object (
    [$id] => 4fcf2f2313cfcd344500000d
)
[id] => 14
[name] => Aryan Roban
[score] => Array (
    [03-06-2012] => 2
    [04-06-2012] => 3
    [05-06-2012] => 5
    [06-06-2012] => 4
)

我需要得分数组的总和(总数),以便

[_id] => MongoId Object (
    [$id] => 4fcf2f2313cfcd2454500000d
)
[id] => 14
[type] => Football
[score] => Array (
    [03-06-2012] => 2
    [04-06-2012] => 3
    [05-06-2012] => 5
    [06-06-2012] => 4
)
[total] => 14

这是想要为类型为Football的每个记录完成。

怎么做?

1 个答案:

答案 0 :(得分:0)

试试这个:

<?php
function addElements( &$v, $k ) {
    $v[ 'total' ] = array_sum( $v[ 'score' ] );
}

$arr = array(
    0 => array('id' => 14,'name' => 'Aryan Roban','score' => array ('03-06-2012' => 2,'04-06-2012' => 3,'05-06-2012' => 5,'06-06-2012' => 4)),
    1 => array('id' => 5,'name' => 'Test','score' => array ('03-06-2012' => 2,'04-06-2012' => 1,'05-06-2012' => 15,'06-06-2012' => 8))
);

array_walk( $arr, 'addElements' );
print_r($arr);
?>

希望这有帮助。