after using $files = new DirectoryIterator() in PHP, how do you sort the items?

后端 未结 2 1362
半阙折子戏
半阙折子戏 2020-12-11 19:35

We can get the files in a directory in PHP by

$files = new DirectoryIterator() 

after that is there an easy way to sort the items in a part

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-11 20:08

    It doesn't look like there is a way to sort the data within the iterator.

    You could place the display data into an intermediary array, with a key of the value you wish to sort by, and call ksort() on the array. This will take two passes over the data however.

    $path = ".";
    $files = new DirectoryIterator($path);
    $files_array = array();
    
    while($files->valid()) {
            // sort key, ie. modified timestamp
            $key = $files->getMTime();
            $data = $files->getFilename();
            $files_array[$key] = $data;
            $files->next();
    }
    ksort($files_array);
    foreach($files_array as $key => $file){
        print $key . " => " . $file . "\n";
    }
    

    edit:

    if you place all of the information that you want to output for the files in the array values, you can simply implode() the array afterwards, instead of looping through the data once again.

提交回复
热议问题