【问题标题】:array_multisort order by value closest to todays datearray_multisort 按最接近今天日期的值排序
【发布时间】:2018-04-24 16:11:31
【问题描述】:

有没有办法将 array_multisort 与自定义 order by 一起使用?我需要按日期顺序显示结果,第一个日期是最接近今天的日期,正如您从下面的代码中看到的那样,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));
      }

【问题讨论】:

    标签: php arrays array-multisort


    【解决方案1】:

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

    希望对你有帮助

    【讨论】:

    • 谢谢,它现在至少以正确的日期顺序显示,虽然最早的日期在前,但更整洁
    • 您可以修改函数以选择离今天最近的日期,甚至可以删除过去的日期
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 2016-03-28
    • 2016-01-31
    • 1970-01-01
    相关资源
    最近更新 更多