gpt4 book ai didi

php - 为我的博客网站创建存档

转载 作者:行者123 更新时间:2023-11-29 09:02:00 25 4
gpt4 key购买 nike

我的数据库表类似于:

id    year   month 
1 2011 november
2 2011 november
3 2011 october

我需要创建一个查询,以便它返回类似的内容:

2011
november
november
october

在 php 脚本中执行此操作的正确查询语法是什么?

这是我使用的代码:

<?php

$uid = $_SESSION['uid'];
$sql = "SELECT year, GROUP_CONCAT(month) AS months FROM articles GROUP BY year";
$res = mysql_query ($sql) or die (mysql_error());
if (mysql_num_rows($res) > 0) {
while ($rows = mysql_fetch_assoc($res)) {
foreach ($rows AS $row) {
echo $row['year'] . "<br>";
$months = explode(",", $row['months']);
foreach ($months AS $m) {
echo $m . "<br>";
}
}
}
}
?>

最佳答案

您可以使用GROUP_CONCAT()返回以逗号分隔的月份列表:

SELECT year, GROUP_CONCAT(month) AS months GROM tbl GROUP BY year

Returns:
2011 november,november,october

或者只选择两列并处理代码中的显示/演示:

SELECT year, month FROM tbl WHERE year = 2011

Returns
2011 november
2011 november
2011 october

在代码中,循环并仅在年份发生变化时显示年份。

更新由于代码示例似乎有必要......

// Results from above GROUP_CONCAT() query already fetched & stored in `$rowset`:    
while ($row = mysql_fetch_assoc($res)) {
$rowset[] = $row;
}

// Now $rowset is a 2D array containing all rows.
foreach ($rowset as $row) {
// Output the year
echo $row['year'] . "\n";

// months are comma-separated via GROUP_CONCAT()
// explode them into an array
$months = explode(",", $row['months']);
foreach ($months as $m) {
// Output the months
echo $m . "\n";
}
}

关于php - 为我的博客网站创建存档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8336032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com