Jimmyborofan
Jimmyborofan

Reputation: 47

order files by part of name

I have an array that contains files=>filenames like so:

$provider1 = ('dnnbzdas04.txt','haethae09.txt','dhsdshnsd05.txt',...,'zdbtebt03.txt');

Similar to a rightmove file the text files have a 'sequence' value at the end,

the files do have unknown filenames BUT the 'sequence' is ALWAYS set, I need to reorder the array so that the result is:

$provider1Ordered = ('hst45ga01.txt','dfa454ba02.txt','zdbtebt03.txt',...,'haethae09.txt');

What I was looking to do is to use a sub_str() to strip away all but the last 6 characters and use this to order the array.

What would be the best way to marry up the new 6 character ordered array to the previous 'rawdata' array and order it in the same fashion?

Please any pointer, help or anything I would be very grateful.

All the best,

Jim

Upvotes: 1

Views: 44

Answers (2)

Pudge601
Pudge601

Reputation: 2068

You could do this with usort. For example

$provider1 = array('dnnbzdas04.txt','haethae09.txt','dhsdshnsd05.txt','zdbtebt03.txt');

usort($provider1, function($a, $b) {
    $a = substr($a, -6, 2);
    $b = substr($b, -6, 2);
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
});

print_r($provider1);

This would output:

Array
(
    [0] => zdbtebt03.txt
    [1] => dnnbzdas04.txt
    [2] => dhsdshnsd05.txt
    [3] => haethae09.txt
)

Upvotes: 2

Laurent S.
Laurent S.

Reputation: 6946

What I would do is based on your initial idea :

use a known sorting algorithm , but instead of comparing the whole values of your array cells, indeed compare the "stripped" version of it. The the "switching" part can be done on the whole cell as usual. For the comparison, I would even focus on solely the sequence number, excluding the extension. Be carefull though that this implies your sequence won't go over 99...

Upvotes: 0

Related Questions