2017-11-11 96 views
0

有沒有辦法使用array_multisort與自定義順序?我需要按照日期順序顯示結果,第一個日期是距離今天最近的日期,正如您從matchDate字段下面的代碼中看到的那樣,字符串以字符串形式出現,然後我將其轉換爲日期值。array_multisort按值最接近今天的日期排序

foreach($matchLists as $matchList) 
{ 

    $fixtures[] = $matchList['matchDate']; 

} 

array_multisort($fixtures, SORT_DESC, $matchLists); 


$newlist = array(); 

    foreach($matchLists as $key => $matchitem) 

{ 
    if(array_key_exists('matchDate', $matchitem)) 
    { 

     $newlist[$matchitem['matchDate']][$key] = ($matchitem); 

    } 


} 
    foreach($newlist as $key => $value) 
    { 
     $fixtureDate = date('D j M Y ga', strtotime($key)); 
     } 

回答

0

是的,看看我的previous answer on SO:

<?php  
$events = array(
    'event1' => array(
     'event_name' => 'Title for Event 1', 
     'event_date' => '2017-11-1' 
    ), 
    'event3' => array(
     'event_name' => 'Title for Event 1', 
     'event_date' => '2017-10-13' 
    ), 
    'event4' => array(
     'event_name' => 'Title for Event 1', 
     'event_date' => '2017-11-10' 
    ), 
    'event2' => array(
     'event_name' => 'Title for Event 1', 
     'event_date' => '2017-10-22' 
    ), 
); 

function date_compare($a, $b) 
{ 
    // note that the variables are calling for the date part of the array 
    // if you are using assoc array from mysql just change the value 
    // to your row name 
    $t1 = strtotime($a['event_date']); 
    $t2 = strtotime($b['event_date']); 
    return $t1 - $t2; 
}  
usort($events, 'date_compare'); 
print_r($events); 

一個在這裏,您有日期的數組,創建date_compare功能,然後usort基於日期排序的數組。

希望這有助於

+0

感謝,這有它現在至少顯示正確的日期順序雖然最早日期第一,雖然 – rmsGreig

+0

更爲整潔,您可以修改功能,同時選擇最接近的日期到今天,甚至可能刪除過去的日期 – Samuel