phparrayssortingtimestampfilenames

Sort an array of filenames naturally by their mid-string timestamp


I have done my fair share of research before posting this and I now need a hand in the right direction. I have a list of ip camera filenames. The filenames are the timestamps itself that I need to sort. I cannot figure out how to sort the dates on the string names. I am thinking I need to convert the string to a readable format for the function strtotime() ? Or is there a way without changing the string? I have no clue how to approach this problem correctly.

I have tried array_multisort($array, SORT_DESC, SORT_NUMERIC); with no luck.

$array = Array ( 'SNAP_CH04_2016_05_15_18_11_05_62777.jpg', 'SNAP_CH01_2016_05_15_18_05_38_63588.jpg', 'SNAP_CH02_2016_05_15_18_05_13_38387.jpg', 'SNAP_CH04_2016_05_15_15_55_28_52502.jpg',  'SNAP_CH04_2016_05_15_14_52_46_26039.jpg',  'SNAP_CH03_2016_05_15_14_52_39_18421.jpg',  'SNAP_CH04_2016_05_15_14_51_34_19005.jpg', 'SNAP_CH02_2016_05_15_14_51_25_9874.jpg', 'SNAP_CH04_2016_05_15_06_12_49_23707.jpg', 'SNAP_CH04_2016_05_15_05_03_09_38176.jpg',  'SNAP_CH04_2016_05_15_03_33_27_29791.jpg', 'SNAP_CH03_2016_05_15_01_59_29_27941.jpg' );

Solution

  • You can use the usort function which let's you define a custom function to compare the strings. Here is how it could work:

    <?php
    
    function timestamp_cmp($a, $b) {
        $first = substr($a, 10);
        $second = substr($b, 10);
        return strnatcmp($first, $second);
    } 
    $array = Array ( 
        'SNAP_CH04_2016_05_15_18_11_05_62777.jpg', 
        'SNAP_CH01_2016_05_15_18_05_38_63588.jpg', 
        'SNAP_CH02_2016_05_15_18_05_13_38387.jpg', 
        'SNAP_CH04_2016_05_15_15_55_28_52502.jpg',  
        'SNAP_CH04_2016_05_15_14_52_46_26039.jpg',  
        'SNAP_CH03_2016_05_15_14_52_39_18421.jpg',  
        'SNAP_CH04_2016_05_15_14_51_34_19005.jpg', 
        'SNAP_CH02_2016_05_15_14_51_25_9874.jpg', 
        'SNAP_CH04_2016_05_15_06_12_49_23707.jpg', 
        'SNAP_CH04_2016_05_15_05_03_09_38176.jpg',  
        'SNAP_CH04_2016_05_15_03_33_27_29791.jpg', 
        'SNAP_CH03_2016_05_15_01_59_29_27941.jpg' 
    );
    
    usort($array,'timestamp_cmp');
    

    Note: If you are on PHP 5.3+, you can do this:

    usort($array,function($a, $b) {
        $first = substr($a, 10);
        $second = substr($b, 10);
        return strnatcmp($first, $second);
    });