我想根据年份将项目组合在一起。它将显示在类似
的表格中2010 -item 1 -item 2 -item 3 2009 -item 4 -item 5 -item 6
我如何使用php和mysql做到这一点?
答案 0 :(得分:1)
SELECT year(datefield) as year, name_of_item
FROM yourtable
ORDER BY year, name_of_item
将是基本的查询结构,然后
$first = true;
$previous_year = null;
echo "<ul>";
while($row = mysql_fetch(...)) {
if ($previous_year != $row['year']) {
... got a new year, start a new list
if (!$first) {
echo "</ul>";
}
$first = false
$previous_year = $row['year']
}
echo "<li>", $row['name_of_item'], "</li>"
}
echo "</ul>"
答案 1 :(得分:1)
您可以将每个数据库行放入一个关联数组中,以year作为键,然后迭代数组以构建列表
$yearItems = array();
while ($row = mysql_fetch_assoc($result)) {
$yearItems[$row['year']][] = $row;
}
foreach($yearItems as $year=>$items)
{
echo $year;
echo "<ul>";
foreach($items as $item)
{
echo "<li>$item</li>";
}
echo "</ul>";
}