Monday, 27 August 2018

PHP sorting a multidimensional array from JSON


PHP multidimensional array sorting is a bit confusing to me.
What I have is an array I formed with json_decode() from a .jsonp file.
It has several variables in each primary array entry. They include "Year", "Month", "Day", "hourTimeStart", and "minuteTimeStart", along with some other information.
I'd like to sort this array by date, so I'd like to first sort by "minuteTimeStart", "hourTimeStart", "Day", then "Month", then "Year", so they're in chronological order.
The array looks like this:
Array (
[0] => Array ( [Year] => 2013 [Month] => February [Day] => 5 [hourTimeStart] => 5 [minuteTimeStart] => 0 [Name] => tht )
[1] => Array ( [Year] => 2013 [Month] => January [Day] => 6 [hourTimeStart] => 2 [minuteTimeStart] => 0 [Name] => gregre)
[2] => Array ( [Year] => 2013 [Month] => March [Day] => 4 [hourTimeStart] => 1 [minuteTimeStart] => 15 [Name] => gregre)
)

Essentially what I'm doing is this:
$databaseFileURL = "../Appointments/AllAppointmentData.jsonp";
    if(file_exists($databaseFileURL)){
        $jsonAppointmentData = file_get_contents($databaseFileURL);
    } else $jsonAppointmentData = "";
    $AppointmentData = json_decode($jsonAppointmentData, true);

Then I want to sort $AppointmentData by the date indicated in each sub-array


You can use usort() to provide a custom comparison function, and mktime() to build the time (in seconds since Epoch) from your Month, Day, Year, Hour, Minute parameters.
Something like this would solve your problem:
    function myDateSort($ar1, $ar2)
    {
       $month1 = //todo: convert $ar1['Month'] string to the corresponding month number
       $date1 = mktime($ar1['hourTimeStart'], $ar1['minuteTimeStart'], 0,  $month1, $ar1['Day'], $ar1['Year'] );

       $month2 = //todo: convert $ar2['Month'] string to the corresponding month number
       $date2 = mktime($ar2['hourTimeStart'], $ar2['minuteTimeStart'], 0,  $month2, $ar2['Day'], $ar2['Year'] );

       //this will sort ascending, change it to $date2 - $date1 for descending
       return $date1 - $date2;
    }

Then just do:
usort($AppointmentData, "myDateSort");

0 comments:

Post a Comment