简体   繁体   中英

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 20:00:00 - 21.08.2010 23: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.
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. I've tried uasort , but I can't use 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).

If you must sort the array in code, you should be able to use usort. I'm assuming you want to sort by startTime

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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