2017-03-22 15 views
0

私はレース名レースIDを持っているレースのテーブル、およびレース日を持っています。PHP配列のマージ問題

私は次の形式でレースのリストを含んでいるでしょう 単一のアレイ(それは、単一のアレイが関数呼び出しを介して返さなければならない)を構築しようとしています

:私は

,,---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 

をほとんどそこに!しかし、私は1つの問題があります。それは作品

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--- 
Gemini Springs AR, 4, 12.14.2015 

明らか$ merged_arrは年間ループ

の各反復でリセット開始されます

関数の結果の配列に年のループのすべてのデータがループするように更新するにはどうすればよいですか?

答えて

1

これをすべて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 
} 
+0

パーフェクト!ありがとう! – mannyotr