博客程序中实现按月份归档

以前使用的方式是将所有的文章日期读出来,然后一笔一笔处理:

function _archives() 
{
    $sql = "select updatetime from tbs_articles";
    $rows = $this->db->getAll($sql);
        
    $archives = array();
    foreach ($rows as $row)
    {
        $month = gmdate("Ym", $row['updatetime'] + $this->_getOption('timeoffset') * 3600);
        if (!array_key_exists($month, $archives))
        {
            $archives[$month] = array('year' => intval(substr($month, 0, 4)), 
                        'month' => intval(substr($month, 4, 2)), 
                        'artnum' => 0);
            $archives[$month]['text'] = $archives[$month]['year'] . '年' . $this->_formatMonth($archives[$month]['month']) . '月';
        }
        $archives[$month]['artnum'] += 1; 
    }
        
    return $archives;
}

修改以后的做法:

function _archives() 
{
    $sql = "select date_format(from_unixtime(updatetime + 3600 * " . $this->_getOption('timeoffset'). "), '%Y%m') as ym, count(1) as artnum from tbs_articles group by ym order by ym";
    $rows = $this->db->getAll($sql);
        
    $archives = array();
    foreach ($rows as $row)
    {
        $archives[$row['ym']] = array('year' => intval(substr($row['ym'], 0, 4)), 
                            'month' => intval(substr($row['ym'], 4, 2)), 
                            'artnum' => $row['artnum']);
    }

    return $archives;
}
原文地址:https://www.cnblogs.com/eastson/p/2837863.html