PHP sorting a multidimensional array from JSON -
php multidimensional array sorting bit confusing me.
what have array formed json_decode()
.jsonp
file.
it has several variables in each primary array entry. include "year", "month", "day", "hourtimestart", , "minutetimestart", along other information.
i'd sort array date, i'd first sort "minutetimestart", "hourtimestart", "day", "month", "year", they're in chronological order.
the array looks 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 i'm doing this:
$databasefileurl = "../appointments/allappointmentdata.jsonp"; if(file_exists($databasefileurl)){ $jsonappointmentdata = file_get_contents($databasefileurl); } else $jsonappointmentdata = ""; $appointmentdata = json_decode($jsonappointmentdata, true);
then want sort $appointmentdata
date indicated in each sub-array
you can use usort() provide custom comparison function, , mktime() build time (in seconds since epoch) month, day, year, hour, minute parameters.
something solve problem:
function mydatesort($ar1, $ar2) { $month1 = //todo: convert $ar1['month'] string corresponding month number $date1 = mktime($ar1['hourtimestart'], $ar1['minutetimestart'], 0, $month1, $ar1['day'], $ar1['year'] ); $month2 = //todo: convert $ar2['month'] string corresponding month number $date2 = mktime($ar2['hourtimestart'], $ar2['minutetimestart'], 0, $month2, $ar2['day'], $ar2['year'] ); //this sort ascending, change $date2 - $date1 descending return $date1 - $date2; }
then do:
usort($appointmentdata, "mydatesort");
Comments
Post a Comment