数据库结果按月和年

时间:2013-11-08 09:10:17

标签: php mysql database joomla

我有一个Joomla 3.1网站,该网站将显示有关所做贡献的报告。报告应按月和年分组。我有一个代码可以从数据库中提取数据但不能将每个月放入单独的<div>,并且每年将其放入父项<div>到其月份。怎么做?这是我的代码。

<?php 
$db = JFactory::getDbo();
$query = $db->getQuery(true);

$query->select(array($db->quoteName('contribution_date'), $db->quoteName('contribution_amount'), $db->quoteName('source')));
$query->from($db->quoteName('contribution'));

$db->setQuery($query);

$results = $db->loadObjectList();
?>

<table class='financial-reports'><th>aaa</th><th>bbb</th><th>ccc</th>
<?php
foreach ( $results as $result) {
   echo '<tr>' . '<td class="fin-rep-date">' . JFactory::getDate($result->contribution_date)->format('d M, Y') . '</td>' . 
                 '<td class="fin-rep-sum">' . $result->contribution_amount . ' ' .'руб.' . '</td>' . 
                 '<td class="fin-rep-source">' . $result->source . '</td>' . '</tr>';
}
?>
</table>

1 个答案:

答案 0 :(得分:3)

我认为简单方法是将结果转换为多维数组,如下所示:

foreach ($results as $result) {
    $resultsArray[JFactory::getDate($result->contribution_date)->format('Y')][JFactory::getDate($result->contribution_date)->format('M')][] = $result;
}

然后你可以这样使用它:

<?php foreach ($resultsArray as $year) : ?>
   <div>
      <?php foreach ($year as $month) : ?>
        <div>
           <?php foreach ($month as $item) : ?> 
             <div>YOUR OUTPUT <?php echo $item->contribution_date; ?></div>
           <?php endforeach; ?>
        </div>
     <?php endforeach; ?>
   </div>
<?php endforeach; ?>