我有一张比赛表,其中包含比赛名称,比赛ID 和比赛日期。
我正在尝试构建一个单个数组(它必须是通过函数调用返回的单个数组),它将包含以下格式的种族列表:
,,---2017---
The Resolution AR, 58, 1.14.2017
Heartbreaker AR, 59, 2.11.2017
,,---2016---
The Blue Ridge AR, 38, 5.21.2016
The Fathers Day AR, 43, 6.18.2016
Adventure Bike (Santos), 54, 7.30.2016
,,---2015---
Gemini Springs AR, 4, 12.14.2015
我快到了!但我有一个问题。
这是我目前的代码:
function get_races() {
// get all the years that have races
$years = $wpdb->get_results("
select DATE_FORMAT(r.race_date,'%Y') year
from race_calendar r
group by DATE_FORMAT(r.race_date,'%Y')
order by DATE_FORMAT(r.race_date,'%Y') desc;
");
// loop through all years that have races
foreach ( $years as $year ) {
// add year header to array
$year_header = array(array ('','','---'.$year->year.'---'));
// get races for this particular year
$races = $wpdb->get_results("
select r.race_name
,r.race_id
,date_format(r.race_date,'%c.%d.%Y') race_date
from race_calendar r
where DATE_FORMAT(r.race_date,'%Y') = ".$year->year."
order by r.race_date;
", ARRAY_N);
// merge the year header and the races into an array
$merged_arr = array_merge($year_header, $races);
}
return $merged_arr;
}
// call function to get list of races
$races = get_races();
// display the list of races (with the year separator)
foreach ( $races as $race )
{
echo $race['0'] . ',' . $race['1'] . ',' . $race['2'] . '<br />';
}
有效。但问题是,上面的代码只显示年循环的最后一次迭代,在本例中为 2015 :
,,---2015---
Gemini Springs AR, 4, 12.14.2015
显然 $ merged_arr 会在年度循环的每次迭代中重置
如何更新它,以便函数中的结果数组包含年循环的所有迭代的数据?
答案 0 :(得分:1)
您可以使用单个查询完成所有操作。只需选择所有行,然后遍历结果并检测年份何时从上一次迭代发生变化,以了解何时输出分隔符行。
$last = null;
$query = <select * from race_calendar order by race_date>
foreach ($query as $row) {
$year = // year of $row['race_date']
if ($year != $last) {
// new year, output separator line
$last = $year;
}
// output data line
}