1

I have this code

if($dateOrder){
    $order = array(filemtime($filter_files[0]));
    for($i=1;$i<$maxnr+1;$i++){
        array_push($order,filemtime($filter_files[$i]));
    }
    array_multisort($order,SORT_DESC,SORT_NUMERIC,$filter_files,SORT_ASC,SORT_NUMERIC);
}
}
//end get image files

How to make possible sort order by filename? For example

picture1 , picture2 , picture3 picture10 , picture11

2
  • Are the filenames always in the format some <string> followed by some <number> ? If that is the case then you can split each filename into two parts - first part is a seq of chars and the 2nd part is an integer. First you need to sort all the filenames by the first key and then with a group where all keys are same you need to sort by the second part which is number. Commented Nov 29, 2014 at 15:20
  • yes, all the images are the same string and incremental numbers. Are you saying that , the code i have is already good? Can you make an example of your proposal? Thank you! Commented Nov 29, 2014 at 18:18

1 Answer 1

1

Here is the working code as per my proposal. The difference from your code is the usage of array_multisort method. PHP array_multiosrt expects single dimension non assoc arrays as its first and second dimension and then the whole data array as the last argument.

<?php
    $dateOrder = true;
    if($dateOrder){
        /*$order = array(filemtime($filter_files[0]));
        for($i=1; $i<$maxnr+1; $i++){
            array_push($order,filemtime($filter_files[$i]));
        }*/
        $order = array('picture1', 'picture2', 'picture20', 'picture9', 'picture3', 'picture10', 'picture11');
        //array_multisort($order,SORT_DESC,SORT_NUMERIC,$filter_files,SORT_ASC,SORT_NUMERIC);
        $names = array();
        for($i=0; $i<count($order); $i++) {
            preg_match('/^(.+?)(\d+)$/', $order[$i], $matches);
            $names[] = array($matches[1], $matches[2]);
        }

        $name = array();
        $number = array();
        foreach ($names as $key => $row) {
            $name[$key]  = $row[0];
            $number[$key] = $row[1];
        }
        array_multisort($name, SORT_ASC, $number, SORT_NUMERIC, $names);
        $output = array();
        foreach ($names as $row) {
            $output[] = $row[0] . $row[1];
        }
        print_r($output);
    }

    ?>

Fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.