array_multisort 按最接近今天的日期排序

array_multisort order by value closest to todays date

有没有办法将 array_multisort 用于自定义订单?我需要结果按日期顺序显示,第一个日期是最接近今天的日期,正如您从下面的代码中看到的那样,matchDate 字段作为字符串出现,我稍后将其转换为日期值。

 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));
      }

是的,看看我的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 根据日期对数组进行排序。

希望对您有所帮助