0

我是 php 新手。我找到了一段从文件夹中获取所有图像的代码。这部分有效。但现在我想在图像下方回显不带扩展名的文件名,在同一个 . 我读了一些关于基本名称和路径的东西,但我没有理解正确......

这有效:

<?php
$files = glob("images/*.*");
for ($i=1; $i<count($files); $i++)
{
$num = $files[$i];
echo '<div class="imgholder"><img src="'.$num.'" class="loadedimg"></div>';
}
?>

我尝试过的(但没有用):

<?php
$path = glob("images/*.*");
$files = glob("images/*.*");
for ($i=1; $i<count($files); $i++)
{
$num = $files[$i];
echo '<div class="imgholder"><img src="'.$num.'" class="loadedimg">';

echo basename($path,".jpg");
echo"</div>";
}
?>

我在网页上收到此错误:basename() 期望参数 1 是字符串,数组在 .../imgloader.php 中给出

4

4 回答 4

0

如果与传递的不同,basename() 仍然具有扩展名。

foreach(glob("images/*.*") as $file) {
    echo '<div class="imgholder"><img src="'.pathinfo($file, PATHINFO_FILENAME).'" class="loadedimg"></div>';
}

此外,如果您只想要 jpg 则在 *.jpg 上使用 glob()。

于 2013-10-14T20:03:37.347 回答
0

As the error suggests, you're trying to use an array as the first parameter for basename().

You probably want this instead:

echo basename($num, '.jpg");

I'd suggest using more descriptive variable names in your code:

$files = glob("images/*.*");
for ($i=1; $i<count($files); $i++)
{
    $img = $files[$i];
    echo '<div class="imgholder"><img src="'.$img.'" class="loadedimg">';
    echo basename($img,".jpg");
    echo"</div>";
}

However, I think it's better to use a foreach loop instead. You can get rid of the count() assignments, and there's no need to declare temporary variables:

foreach (glob("images/*.*") as $img) {
    echo '<div class="imgholder"><img src="'.$img.'" class="loadedimg">';
    echo basename($img,".jpg");
    echo"</div>";
}

The second parameter in basename() is optional, and is only necessary if you want to get the trailing components for images with .jpg extension.

于 2013-10-14T19:45:16.877 回答
0

使用 foreach 循环...

foreach ($path as $p)
    {
    echo basename($p, ".jpg");
    }

您定义为 $path 的是一个路径数组,为了清楚起见,可能会更改其名称。

于 2013-10-14T19:48:55.020 回答
0

这是因为您必须显示当前元素。尝试:

basename($files[$i]);
于 2013-10-14T19:50:06.880 回答