0

How can I order times and dates from smallest to largest in order to extract data in a chronological order using PHP (not MySQL)?

I have an array with objects with various "keys" which include the time and the event.

Here is an edited var_dump of what I have:

[0] => object {
    ["time"] => "24/06/2015 - 12:30 PM"
    ["event"] => "Another event"
}
[1] => object {
    ["time"] => "24/06/2015 - 08:45 AM"
    ["event"] => "Event"
}
[2] => object {
    ["time"] => "25/06/2015 - 09:50 AM"
    ["event"] => "Yet another event"
}

I want the output to be something similar to:

24/06/2015:

Event

Another event

25/06/2015:

Yet another event

Thanks in advance.

p1xel
  • 294
  • 2
  • 10
  • possible duplicate of [Sort array of objects by date field](http://stackoverflow.com/questions/7127764/sort-array-of-objects-by-date-field) – Ugur Jun 24 '15 at 08:10

2 Answers2

0

One way to do it is to rearrange the array so keys are timestamp values:

$newArr = [];
foreach($objArr as $obj) {
  $newArr[ strtotime( $obj->time ) ] = $obj;
}

Then, you can use ksort() or krsort().

marekful
  • 14,986
  • 6
  • 37
  • 59
  • strtotime has trouble reading the date I provide. It's in a format it doesn't understand. – p1xel Jun 29 '15 at 05:35
0

You can use the usort standard php function with the following custom function :

function sortbytobjtime($a, $b){
    $adate = date_create_from_format('d/m/Y - h:i a', $a->time);
    $bdate = date_create_from_format('d/m/Y - h:i a', $b->time);
    if ( $adate == $bdate ) return 0;
    return ( $adate < $bdate) ? -1 : 1;
}

usort($arr, 'sortbytobjtime');

$arr being an array filled with objects as described in your question. Note that this solution needs PHP 5 with version >= 5.3.0 in order to have the DateTime class available.