【发布时间】:2014-02-04 10:49:27
【问题描述】:
我有一些 PHP 脚本可以读取图像目录并回显用户搜索的结果。
我需要找到一种方法从目录中对这些搜索结果进行排序,我知道您可以在数组上使用 natsort() 但这无济于事,因为结果不在数组中,只是一个 while 语句。
有谁知道这是否可行?或者也许更容易调整我的代码以首先将文件名添加到数组中?
<?php
$dir = get_post_meta($post->ID, "Library", true);
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if(stristr($file,$_POST['image_search'])){
echo ('<li><div class="thumb-contain"><a href="/'.$dir . $file.'" class="photo-link" rel="attachment"><img src="/asset-thumbs/'. $file .'" /></a><br/><p><a href="/'.$dir . $file.'" class="photo-link" target="_blank">View image</a> | <a href="/download.php?download_file='.$dir . $file.'">Download image</a> <p>'. $file .'</p></div></li>');
}
}
closedir($dh);
}
}
?>
好的,我通过将结果添加到数组中来让它工作 - 我不是 PHP 向导,所以如果有人发现任何可能更清洁的东西,那就太棒了,否则感谢您的帮助。
<?php
$dir = get_post_meta($post->ID, "Library", true);
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if(stristr($file,$_POST['image_search'])){
$files[] = $file;
}
}
closedir($dh);
natsort($files);
foreach($files as $file) {
echo ('<li><div class="thumb-contain"><a href="/'.$dir . $file.'" class="photo-link" rel="attachment"><img src="/asset-thumbs/'. $file .'" /></a><br/><p><a href="/'.$dir . $file.'" class="photo-link" target="_blank">View image</a> | <a href="/download.php?download_file='.$dir . $file.'">Download image</a> <p>'. $file .'</p></div></li>');
}
}
}
?>
【问题讨论】:
-
为什么不遍历
readdir结果并将项目添加到数组中。然后对该数组进行排序?