简体   繁体   English

需要帮助对多数组进行排序

[英]Need help sorting multi array

I see a lot of examples here, but it's not working for me. 我在这里看到了很多示例,但是对我来说不起作用。

I have a list of sorted events retrieved from my DB: 我有一个从数据库中检索到的已排序事件的列表:

16.08.2010 12:00:00 - 21.08.2010 20:00:00 16.08.2010 12:00:00 : 21.08.2010 20:00:00
16.08.2010 20:00:00 - 21.08.2010 23:00:00 16.08.2010 20:00:00 : 21.08.2010 23:00:00
18.08.2010 17:00:00 - 18.08.2010 19:00:00 18.08.2010 17:00:00 : 18.08.2010 19:00:00

As you can see, the first event is from 16.08 to 21.08. 如您所见,第一个事件是从16.08到21.08。
I need to "chop this up" so that I get one entry foreach day. 我需要“切碎”,以便每天获得一份。

This is my function: 这是我的功能:

  function fullList( $data ) {
    $ev = $data['events']; 
    $events = array();

    // Loop through each event. If event spans over several days, add each day in to new event list  
    foreach($ev as $e) :
      $endDate = strtotime(date('Y-m-d 23:59:59', strtotime($e->endTime)));
      $current = strtotime($e->startTime);

      // Copy event so data is not overwritten
      $newEv = $e;

      while ($current <= $endDate) {

          //Set start date of event to new date
          $newEv->startTime = date('d.m.Y H:i:s', $current);

          // Add events to new event list
          array_push($events,$newEv);

          //Go to next date
          $current = strtotime('+1 day', $current);
      }      
    endforeach;
    // Need to sort $events here
  }

Now $events contains all events, but it's not sorted by date. 现在, $events包含所有事件,但未按日期排序。 I've tried uasort , but I can't use uasort($array, 'cmp'); 我已经尝试过uasort ,但是不能使用uasort($array, 'cmp'); .

How can I go about sorting this array by date? 我该如何按日期对该数组进行排序?

您是否尝试过自然排序算法?

As Nazariy mentioned, you would be better off pre-sorting the events at the source (assuming they come from a DB). 正如Nazariy所述,最好从源头对事件进行预排序(假设事件来自数据库)。

If you must sort the array in code, you should be able to use usort. 如果必须使用代码对数组进行排序,则应该可以使用usort。 I'm assuming you want to sort by startTime 我假设您要按startTime排序

usort($events, function($a, $b) {
    return strtotime($a->startTime) - strtotime($b->startTime);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM