如何在嵌套数组中获取我的集合中的总和?

时间:2014-12-24 14:05:30

标签: php mongodb aggregation-framework

我有这个系列:

...
"votes": [
 {
   "track1": [
     {
       "facebook": NumberLong(1) 
    } 
  ],
   "track2": [
     {
       "google": NumberLong(1),
       "twitter": NumberLong(1) 
    } 
  ] 
} 

]     ...

我想获得track1或track2的投票总和,所以我做的是:

$match = array(
            'app_id' => (int)$appId,
            'campaign_id' => (int)$campaign_id
        );

        $group = array(
            '_id' => 'votes.0.'.$_t.'.0.facebook', //$_t => track id
            'total' => array(
                '$sum' => '$votes.0.'.$_t.'.0.facebook'
            )
        );

        $res = $collection->aggregate(array(
                array(
                    '$match' => $match
                ),
                array(
                    '$group' => $group
                )
            )
        );

        $res_facebook = (int) $res['result'][0]['total'];

结果:0

问题出在哪里?

1 个答案:

答案 0 :(得分:0)

不确定它是否会起作用,我没有检查,但我有类似的东西。 这就是我要解决的问题:

$votes_array = json_decode($votes_array_json,TRUE);

$total_votes = 0;
foreach($votes_array as $track) {
    foreach($track as $social_network => $votes) {
          $total_votes = $total_votes + $votes;
    };
};