ScrollerS
ScrollerS

Reputation: 11

Php sort by filename

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

Upvotes: 1

Views: 191

Answers (1)

Diptendu
Diptendu

Reputation: 2158

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

Upvotes: 1

Related Questions