0

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?

5
  • 3
    It would be more efficient to do it via MySQL ORDER BY parameter. Commented Jan 31, 2011 at 1:16
  • Why can't you use uasort (or usort which would be more appropriate)? Commented Jan 31, 2011 at 1:18
  • 1
    FYI, you aren't copying $e by assigning it to $newEnv, you just creating another reference. To copy an object, use clone Commented Jan 31, 2011 at 1:28
  • @Nazariy - initial list is retrieved from DB ordered by s.time. Thanks @Phil Brown - I forgot that. Commented Jan 31, 2011 at 2:04
  • You can use few columns in ORDER statement and group them if necessary, like: ORDER BY event_date DESC, event_time ASC Commented Jan 31, 2011 at 2:18

2 Answers 2

2

Have you tried natural sorting algorithm?

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

I've added some extra info in my Q. The initial event list is retrieved in order from DB. Thanks for the tip on usort. I'll test this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.