我有以下MySQL查询(timestamp显然是在Unix时间内):

SELECT usr_id, CONCAT(YEAR(FROM_UNIXTIME(timestamp)), "/", MONTH(FROM_UNIXTIME(timestamp)), "/", DAY(FROM_UNIXTIME(timestamp))) as date_stamp
FROM table
ORDER BY YEAR(FROM_UNIXTIME(timestamp)), MONTH(FROM_UNIXTIME(timestamp)), DAY(FROM_UNIXTIME(timestamp));

这会产生如下结果:
$arr = array(
    array('usr_id'=>3, 'date_stamp'=>'2011/6/6'),
    array('usr_id'=>2, 'date_stamp'=>'2011/6/20'),
    array('usr_id'=>2, 'date_stamp'=>'2011/6/20'), // same id and date as above
    array('usr_id'=>5, 'date_stamp'=>'2011/6/20'), // same date as above
    array('usr_id'=>1, 'date_stamp'=>'2011/6/21'),
    array('usr_id'=>4, 'date_stamp'=>'2011/6/21'), // same date as above
    array('usr_id'=>2, 'date_stamp'=>'2011/6/21'), // same date as above...
        //... and same id as a day before
);

我想把它变成这样:
$arr = array(
    array('sum'=>1, 'date_stamp'=>'2011/6/6'),
    array('sum'=>3, 'date_stamp'=>'2011/6/20'), // +2 as one of the 3...
        //... for this date was a duplicate
    array('sum'=>5, 'date_stamp'=>'2011/6/21'), // +2 as one of the 3...
        //... was already there on a different day
);

这是我尝试过的,但我后来才意识到,它只考虑给定日期的唯一性,而不是我想要的整个数组:
$sum = 0;
$tempRes = array();
$result = array();
$date = null;
foreach($arr as $row)
{
    $date = $row['date_stamp'];
    if (!in_array($row['usr_id'], $tempRes))
        $tempRes[$date][] = $row2['usr_id'];
}
foreach ($tempRes as $date2 => $ids)
{
    $sum += count($ids);
    $result[] = array($date2, $sum);
}

基本上,目的是生成每天usr_id个数的累积和,并确保在整个数组中相同的usr_id只被计算为一个,即按天排序的唯一usr_id个数的累积和。
如果您有更好地优化MySQL查询的想法,也欢迎这样做。
编辑:我希望“累积”发生在整个数组中,而不仅仅是每天,如我的示例输出,即第1天是1,第2天是3(1+2),第3天是5(3+2)。。。等。

最佳答案

您可以首先按天对唯一用户进行分组,如下所示:

foreach ($arr as $item) {
    $days[$item['date_stamp']][$item['usr_id']] = 1; // value is irrelevant
}

然后,您可以创建一个所有用户的数组,将每天的用户合并到其中,并计算结果以获得累积和。
$all_users = array();
foreach ($days as $day => $users) {
    $all_users = $all_users + $users;
    $result[] = array('sum' => count($all_users), 'date_stamp' => $day);
}

关于php - 嵌套数组中按其他元素排序的唯一元素的累积总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36780339/

10-15 12:33