晚上好,我正在尝试自学php,因为我去了,并决定尝试在工作中为我们的LAN服务器构建一些东西。
我有以下代码可以工作并显示目录中的图像,我正在使用它,因为我正在系统中建立工作预订并按作业编号命名图像。
为此我命名图像测试但是如果有任何图像则会出现问题。
<?php
$directory = "saved_images/";
$images = glob("" . $directory . "test*.jpg");
$imgs = '';
foreach($images as $image){ $imgs[] = "$image"; }
$imgs = array_slice($imgs, 0, 20);
$result = count($imgs);
if ($result == 0)
{
$img="No Photos";
echo $img;
}
} else {
foreach ($imgs as $img) {
echo "<img src='$img' /> ";
}}
?>
问题是,如果没有任何照片,我希望它不回应照片而不是以下错误
array_slice() expects parameter 1 to be array,
参考这一行
$imgs = array_slice($imgs, 0, 20);
和
Invalid argument supplied for foreach()
参考这一行
foreach ($imgs as $img)
我见过有类似问题的人,但遗憾的是他们被建议忽略这个问题并关闭错误报告,这看起来并不正确,我只是问这个导致其他问题。该项目,并想知道如何解决这个问题所以,如果我再次遇到它,我知道该怎么做。
答案 0 :(得分:1)
为什么要将$imgs
初始化为字符串?
$imgs = '';
然后将其视为数组?
foreach($images as $image){ $imgs[] = "$image"; }
如果您将其初始化为数组,例如
$imgs = array();
然后,即使foreach没有向数组添加任何对数,当你将它传递给array_slice
时,它仍然是一个(空)数组。
基本上,你创造一个披萨,然后想知道为什么PHP抱怨它不是巧克力蛋糕。
答案 1 :(得分:1)
涡卷
$imgs = array_slice($imgs, 0, 20);
在if(isset())
语句中,如此
if(isset($imgs)){
$imgs = array_slice($imgs, 0, 20);
}
如果仍然无法添加
&& count($imgs) > 0
到它
编辑:
以及@MarcB所说的内容,将$imgs = '';
替换为$imgs = array();
答案 2 :(得分:1)
您需要做的就是将$imgs
设置为数组(不是字符串),并检查$imgs
是否为空。当你在这里时,你会想要检查$images
是否为空。
$directory = "saved_images/";
$images = glob("" . $directory . "test*.jpg");
// since the entire script relies on $images not being empty,
// we should check for that to be sure before moving on
// you can also test for glob() returning FALSE on error, if you anticipate that it might
if ( ! empty($images) ) {
$imgs = []; // this should be set as an array, not a string
foreach ($images as $image)
{
$imgs[] = $image;
}
if ( empty($imgs) ) {
echo 'No Photo';
}
else {
$imgs = array_slice($imgs, 0, 20);
$result = count($imgs);
foreach ($imgs as $img)
{
echo "<img src='$img'> ";
}
}
}
else {
echo 'No images in ' . $directory . ';
}
答案 3 :(得分:0)
您可以使用php函数is_array($myArrayVar)
(PHP Net)来测试$img
是否是您使用array_slice($imgs, 0, 20)
的行之前的数组。类似的东西:
if (is_array($imgs)){
// $imgs is an array
} else {
//$imgs is not an array
}