0

我正在尝试显示一些给定日期范围的统计数据。在表行中有许多 ID 并试图计算它自己的 ID 的总分钟数。

当前返回值如下:

{"id":"25","minute":13}
{"id":"17","minute":12}
{"id":"16","minute":10}
{"id":"17","minute":10}
{"id":"16","minute":4}
{"id":"34","minute":5}
{"id":"17","minute":21}
{"id":"30","minute":12}
{"id":"30","minute":13}
{"id":"30","minute":50}

控制器

public function actionStats()  {
    if (isset($_POST['begin'], $_POST['end'])) {
        $begin = strtotime($_POST['begin']);
        $end = strtotime($_POST['end']);

        $Criteria = new CDbCriteria();
        $Criteria->condition = "created >= $begin and  created <= $end and status=1";
        $transcripts = Transcripts::model()->findAll($Criteria);

        foreach($transcripts as $transcript)  {
            $op = $transcript->opID;
            $minute = $transcript->ended - $transcript->created;

            echo json_encode(array("id" => $op, "minute" => floor($minute/60)));
        }
    }       
}
4

2 回答 2

0

在 MySQL 查询中添加它怎么样?例如具有以下SUM功能:

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

于 2012-07-16T20:48:43.073 回答
0

我会将您的代码修改为:

public function actionStats()
{

    if (isset($_POST['begin'], $_POST['end']))
    {
        $begin = strtotime($_POST['begin']);
        $end = strtotime($_POST['end']);

        $Criteria = new CDbCriteria();
        $Criteria->condition = "created >= $begin and  created <= $end and status=1";
        $transcripts = Transcripts::model()->findAll($Criteria);

        $transcriptTotals = array();
        foreach($transcripts as $transcript)
        {

            $op = $transcript->opID;
            $minute = $transcript->ended - $transcript->created;
            if (array_key_exists($op, $transcriptTotals)) {
                $transcriptTotals[$op] += floor($minute/60);
            } else {
                $transcriptTotals[$op] = floor($minute/60);
            }
        }
        echo json_encode($transcriptTotals);
    }       

}

这应该会产生如下所示的输出:

{'1':'2', 'id':'sumOfMinutes', etc}

如果您的 JSON 需要像上面指定的那样,您将有如下代码:

foreach ($transcriptTotals as $id=>$sum) {
    echo json_encode(array('id'=>$id, 'minutes'=>$sum));
}
于 2012-07-16T20:49:26.483 回答