как сортировать файлы по php - PullRequest
0 голосов
/ 15 ноября 2010

Я немного запутался, как я могу сортировать свои результаты. Я возвращаю список файлов в каталоге и нужно, чтобы они как-то сортировались ...

// Start directory
getDirectory('../gallery/photos');

function getDirectory( $path = '.', $level = 0 ){

 // Directories to ignore when listing output. 
 $ignore = array( '.', '..' ); 

 // Open the directory to the handle $dh
 $dh = @opendir( $path ); 

 // Loop through the directory 
 while( false !== ( $file = readdir( $dh ) ) ) {

  // Change filename to display date
  $displaydate= date('jS M Y', strtotime($file)); 

  // Check that this file is not to be ignored 
  if( !in_array( $file, $ignore ) ) { 

   // Indent spacing for better view
   $spaces = str_repeat( ' ', ( $level * 5 ) );

   // Show directories only
   if(is_dir( "$path/$file" ) ){ 

    // Re-call this same function but on a new directory. 
    // this is what makes function recursive. 
    echo "$spaces<a href='$path/$file'>$displaydate</a><br />";
    getDirectory( "$path/$file", ($level+1) ); 
   } 
  } 
 }
 // Close the directory handle 
 closedir( $dh ); 
} 

где бы я применил функцию сортировки?

спасибо

Ответы [ 3 ]

1 голос
/ 15 ноября 2010

ответом будет добавление ваших записей в массив и сортировка

, но серьезно.однако ваш код (я не знаю, откуда вы взяли этот фрагмент) выглядит действительно устаревшим.есть гораздо более элегантные способы сделать это.

, например glob

, просто чтобы ваш код был модифицирован так, чтобы по существу делать то, что вы хотите, и ничего, что у вас может бытьследующее:

// Start directory
getDirectory('../gallery/photos');

function getDirectory( $path = '.', $level = 0 ){

 // Directories to ignore when listing output. 
 $ignore = array( '.', '..' ); 

 // Open the directory to the handle $dh
 //$dh = @opendir( $path ); 

 // Loop through the directory 

 //while( false !== ( $file = readdir( $dh ) ) ) {
  $files = $files = glob($path.DS."*");
  sort($files);
  foreach($files as file) {
  // Change filename to display date
  $displaydate= date('jS M Y', strtotime($file)); 

  // Check that this file is not to be ignored 
  if( !in_array( $file, $ignore ) ) { 

   // Indent spacing for better view
   $spaces = str_repeat( '&nbsp;', ( $level * 5 ) );

   // Show directories only
   if(is_dir( "$path/$file" ) ){ 

    // Re-call this same function but on a new directory. 
    // this is what makes function recursive. 
    echo "$spaces<a href='$path/$file'>$displaydate</a><br />";
    getDirectory( "$path/$file", ($level+1) ); 
   } 
  } 
 }
 // Close the directory handle 
 closedir( $dh ); 
} 
0 голосов
/ 15 ноября 2010

Я рекомендую отказаться от этой функции и использовать glob

$files = glob("dir/*");
sort( $files );
0 голосов
/ 15 ноября 2010

Вам нужно будет накапливать результаты каждой итерации, а не передавать их пользователю.Затем, после завершения функции, она должна отсортировать результаты.Однако сортируйте результаты только тогда, когда $level равно 1.Если вы этого не сделаете, результаты будут отсортированы после каждой рекурсии.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...