我有一个简单的函数,它返回一个有效的图像路径来显示。它传递了为我的数据库中的特定行存储的URL。基本功能是:
它完美无缺,除非文件夹只包含一个名为' original.jpg'的文件,它会显示默认图像。如果我添加另一个文件,它可以使用' original.jpg'。如果我将其重命名为" original.jpeg'或者' ori.jpg' (或更短)它的工作原理。这是我遇到过的唯一一种行为方式。
function displayFile($file){
$imgPath = "./img/path/";
// If folder was specified or file doesn't exists; use first available file
if( substr($file, -1) == '/' || !file_exists($imgPath . $file) ){
// Extract base path
$file = strstr( $file, '/', true );
$handle = opendir($imgPath . $file);
$entry = readdir($handle);
$firstFile = '';
while (false !== ($entry = readdir($handle))) {
if( substr($entry, 0, 1) != '.' ){
$firstFile = $entry;
break; // This break isn't the problem
}
}
// No file found; use default
if( $firstFile == '' ){ return $imgPath . "paw.png"; }
// Found a file to use
else{ return $imgPath . $file . '/' . $firstFile; }
} else {
// File name is valid; use it
return $imgPath . $file;
}
closedir($imgPath);
}
答案 0 :(得分:2)
你要两次调用readdir,基本上总是跳过第一个条目。
$entry = readdir($handle);
删除该行,你应该好好去。
答案 1 :(得分:1)
您需要执行许多不必要的操作来检索文件。
这是您的功能的修改版本,它应该按预期工作并且它很简短:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:andorid="http://schemas.android.com/tools">
<item andorid:id="@+id/action_refresh"
android:title="@string/action_refresh"
app:showAsAction="never" />
</menu>
答案 2 :(得分:0)
@knrdk绝对正确,但要解释看似不稳定的行为:它有时而不是其他行为的原因是因为排序。缩小功能到:
function displayFile($file){
$imgPath = "./img/path/";
$file = strstr( $file, '/', true );
$handle = opendir($imgPath . $file);
$entry = readdir($handle);
while (false !== ($entry = readdir($handle))) {
echo $entry . ' ';
}
closedir($imgPath);
说明行为
/* folder/[1.jpg] */
displayFile('folder'); // Output: . 1.jpg
/* folder/[original.jpg] */
displayFile('folder'); // Output: . ..
/* folder/[original.jpeg] */
displayFile('folder'); // Output: original.jpg .
// Not entirely sure why that's different, but there it is
/* folder/[1.jpg, original.jpg] */
displayFile('folder'); // Output: original.jpg .. .