我有一个自定义的wordpress表,并试图将数据库中的所有行按年份分隔。我的代码:

echo "<table width='100%'>";
for ($year = date("Y"); $year >= 2017; --$year) {
    echo ("<tr><th>$year</th></tr>");
    echo ("<tr><th>Champions</th>");

    echo ("<th>Score</th>");

    echo ("<th>Date</th></tr>");

  global $wpdb;
        $clubmatch = $wpdb->get_results("SELECT * FROM wp_club ORDER BY gamedate DESC");

    foreach($clubmatch as $row){

      echo "<tr><td>" . $row->names . "</td>";
        echo "<td>" . $row->score . "</td>";
        echo "<td>" . $row->gamedate . "</td></tr>";
    }
    echo ("<tr><td style='padding: 20px;'></td></tr>");


}
echo '</table>';

这将在屏幕上显示以下内容:
2018
Champions   Score   Date
Sam Jones - Peggy Jones    81.43    2018-03-01
Joseph Parks - Carmen Parks    70.85    2017-12-17

2017
Champions   Score   Date
Sam Jones - Peggy Jones    81.43    2018-03-01
Joseph Parks - Carmen Parks    70.85    2017-12-17

我怎么才能让它像这样显示出来?每排在适当的年份下?
2018
Champions   Score   Date
Sam Jones - Peggy Jones    81.43    2018-03-01

2017
Champions   Score   Date
Joseph Parks - Carmen Parks    70.85    2017-12-17

提前谢谢!

最佳答案

更改SQL查询,以便按字段gamedate的年份过滤结果。所以使用这个:(为了清楚起见,代码缩进了)

$clubmatch = $wpdb->get_results(
    "SELECT * FROM wp_club " .
    "WHERE YEAR(gamedate) = '$year' " .
    "ORDER BY gamedate DESC"
);

…而不是:
$clubmatch = $wpdb->get_results("SELECT * FROM wp_club ORDER BY gamedate DESC");

09-18 16:06