I have some PHP script that reads an image directory and echos out the results of the users search.
I need to find a way of sorting these search results from the directory, I know you can use natsort() on an array but this does not help as the results are not in an array, just a while statement.
Does anyone know if this is doable? Or maybe it would be easier to adapt my code to add the file names to an array first?
<?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);
}
}
?>
Ok I got it working by adding results into an array - I am not a PHP wizard so if anyone spots anything that could be cleaner that would be fantastic, otherwise thanks for your help.
<?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>');
}
}
}
?>
您可以使用函数scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] )
-它返回数组并支持排序(作为选项)。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.