Forum Moderators: coopster

Message Too Old, No Replies

Sorting an array by date

         

Gilead

6:36 pm on Apr 22, 2019 (gmt 0)

10+ Year Member



This topic may have been covered multiple times, but bear with me.
I have data taken from a mysql database via PHP. One of the fields is Date of Service, which is saved in the YYYY/MM/DD format to make MYSQL happy. The results are going into a json object to be used by and returned to a c# application. I want to be able to sort the array by date. Currently, it will show the dates in the order of entry. So if someone adds a new data set with the date of 4/20/2019, then adds an earlier date of 3/19/2019, the information will display 4/20 first and 3/19 second. I want to show 3/19 first. I'm open to sorting the json object or the array, which ever is easier. Data type is date in the short form.

if($result ->num_rows>0)
{
$rows=array();
while($row=$result->fetch_assoc())
{
$rows[]=$row;

}
echo json_encode($rows);
}


Thanks for the help!

LifeinAsia

9:24 pm on Apr 22, 2019 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



which is saved in the YYYY/MM/DD format to make MYSQL happy
Not sure I understand this... MySQL saves date values as a date value (several options). Whether you display a particular value as YYY/MM/DD or M/D/YY or YYYY-MM-DD is completely independent of storage. And if you sort the query in ascending (default) order, you'll get 3/19 before 4/20.

If the field is characters instead of date (or timestamp), then all bets are off as character sorting and date/time sorting don't always jibe.

If you're not specifying the sort order in your query, then you're going to get the data in whatever way MySQL decides to spit it out. I'd definitely specify the sort order in the query instead of using additional processing to re-sort in PHP- MySQL is much more efficient that PHP for that.

penders

11:57 pm on Apr 22, 2019 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



If the field is characters instead of date...


Although if the date was consistently stored as a string in the form "YYYY/MM/DD" then MySQL ordering should still be correct, assuming the data is all coming from a single table.

Gilead

4:10 pm on Apr 23, 2019 (gmt 0)

10+ Year Member



Thanks!