【发布时间】:2014-04-20 10:34:02
【问题描述】:
我有一个包含时间戳的数组。我想知道 Facebook 等应用程序如何集群帖子。为清楚起见,假设您有一组时间戳,并希望按以下方式对时间戳进行分组:
- 今天
- 本周
- 本月
- 一月、二月、三月
- 2013
- 2012年等
重要的是,“本月”中的帖子不要在“本周”中重复,而这些帖子也不要在“今天”中重复。另外,我在上面对一月、二月和三月进行了硬编码。该脚本应在技术上检测一年中的前几个月。我无法完全编写一个算法来完全实现这一点。这就是我所拥有的。
<?php
$posts = array(
array('post_id' => 7, 'timestamp' => '2014-04-20 20:17:49'),
array('post_id' => 6, 'timestamp' => '2014-04-07 20:17:49'),
array('post_id' => 5, 'timestamp' => '2014-03-17 20:17:49'),
array('post_id' => 4, 'timestamp' => '2014-02-14 20:17:49'),
array('post_id' => 3, 'timestamp' => '2014-01-09 20:17:49'),
array('post_id' => 2, 'timestamp' => '2013-09-23 20:17:49'),
array('post_id' => 1, 'timestamp' => '2012-09-23 20:17:49')
);
$today = strtotime(date("Y-m-d"));
$week_start = strtotime('last sunday', strtotime('tomorrow'));
$month_start = strtotime(date_create(date("Y-m-d"))->modify('first day of this month')->format("Y-m-d"));
$year_start = strtotime(date_create(date("Y-m-d"))->modify('first day of january 2014')->format("Y-m-d"));
foreach ($posts as $post)
{
$item = strtotime($post['timestamp']);
if ($item >= $today)
{
// Today
echo '<br><br>' . 'Today' . '<br>';
echo $post['post_id'] . '<br>';
}
else if (($item <= $today) && ($item >= $week_start))
{
// This week
echo '<br><br>' . 'This week' . '<br>';
echo $post['post_id'] . '<br>';
}
else if (($item <= $week_start) && ($item >= $month_start))
{
// This month
echo '<br><br>' . 'This month' . '<br>';
echo $post['post_id'] . '<br>';
}
else if (($item <= $month_start) && ($item >= $year_start))
{
// This year
echo '<br><br>' . 'This year' . '<br>';
echo $post['post_id'] . '<br>';
}
}
此脚本在“本月”之前有效,其余的仅按“今年”进行聚类。我无法按月对它们进行分类,也无法在今年之前进行分类。实现这种级别的聚类并快速完成的最佳方法是什么?
【问题讨论】: