0

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.

0

If you change the saved date format to YYYY-MM-DD HH:MM (always with leading zeroes). You can use the usort() array sorting function from php.

usort( $array, function( $a, $b ) {
    return strcomp( $a['show_date_and_time'], $b['show_date_and_time'] );
} );

Without changing the date format you need a more complex compare callback:

usort( $array, function( $a, $b ) {
    $date_a = date_create_from_format( 'j-m-Y H:i', $a['show_date_and_time'] );
    $date_b = date_create_from_format( 'j-m-Y H:i', $b['show_date_and_time'] );
    if ( $date_a > $date_b ) {
        return 1;
    } else if ( $date_a == $date_b ) {
        return 0;
    }
    return -1;
} );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy