简体   繁体   中英

Need Help Sorting Array with Timestamp in PHP

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' );

Any advice is appreciated. Trying to learn.

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);
});

As long as you're ok with sorting the included "SNAP_CH_04" part of the name, you can just use sort() to sort the array with no conversion whatsoever.

sort($array);

If you need to strip that part out, you can use substr then sort() , like this:

for ($a = 0; $a < count($array); $a++)
{
    $array[$a] = substr($array,10);
}

sort($array);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM