Array sorting assistance

Hi guys,

I have the following array that I want to sort, how would I approach this as it only has one key / column?

Short brief: I have movies that are saved in a custom post type. some have time allocated using a date picker and saved in a meta field. The reason I check if they are not empty is for the same reason.

This is what my script looks for like (no filter as yet):

$airing_times =  get_field('airing_date_and_time');

if( !empty($airing_times) ) {
    var_dump($airing_times);
}

This is what my array looks like:

Array ( [0] => Array ( [show_date_and_time] => 17-9-2015 14:00 ) [1] => Array ( [show_date_and_time] => 17-7-2025 18:30 ) ) Array ( [0] => Array ( [show_date_and_time] => 18-1-2018 12:03 ) [1] => Array ( [show_date_and_time] => 26-4-2017 16:00 ) ) Array ( [0] => Array ( [show_date_and_time] => 17-8-2026 12:00 ) [1] => Array ( [show_date_and_time] => 17-12-2021 12:00 ) )

I basically want to sort the time - from old to future.

isn’t there some option you can pass to get_field() to make the DB sort it for you?

if that’s not possible, you’d have to resort to http://php.net/usort using http://php.net/datetime or http://php.net/strtotime.

Would it be easier to sort if the date/time fields were in a different format? That is, if the date was YYYYMMDD would a standard sort routine simplify the job?

I can change the format. My question was since there is only one array key, how to I got about doing it?

You’re more than welcome to give an example using: YYYYMMDD

Actually, I think it’s just like @Dormilich said above, use usort or, if you need to maintain the relationship between the key and the contents, uasort:

uasort($yourrray, function($a, $b) {
  if ($a['show_date_and_time'] > $b['show_date_and_time']) return -1;
  if ($a['show_date_and_time'] < $b['show_date_and_time']) return 1;
  return 0;
});

I can’t remember which “direction” that will sort in, if it’s the wrong way around for you then either swap the < and > signs, or swap the -1 and 1 return values.

All that’s happening is uasort is calling the function I’ve defined below it to perform the comparison to see whether array elements need to be moved. You could retain your original date / time format, but that would need you to extract the year, month and date within the function to do the comparison. Swapping them to YYYYMMDD can just use ASCII values to get them in order, so much simpler to code.

I think that will do it, it’s similar to another question someone asked a while back on a similar topic.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.