注意:未定义的偏移量:不同的行

我正在尝试显示存储在2个数组中的图像的元数据…

当图像没有名称时,我想显示“ no-name”。这是我现在显示这些的方式:


$imgs = array('img 1','img 2','img 3','img 4','img 5','img 6');

$imgNames = array('name 1','name 2','name 3',);


foreach($imgs as $files => $img)

{

    echo 'Image: '.$img.' and Name: '.$imgNames[$files].'<br>';

};

我期望输出:


Image: img 1 and Name: name 1

Image: img 2 and Name: name 2

Image: img 3 and Name: name 3

Image: img 4 and Name: no-name

Image: img 5 and Name: no-name

Image: img 6 and Name: no-name

但实际输出是:


Image: img 1 and Name: name 1

Image: img 2 and Name: name 2

Image: img 3 and Name: name 3

Notice: Undefined offset: 3 in XX.php …

Image:img 4 and Name: 

Notice: Undefined offset: 4 in XX.php …

Image:img 5 and Name: 

Notice: Undefined offset: 5 in XX.php …

Image:img 6 and Name: 

如何解决此问题以显示默认的“无名称”字符串?


繁华开满天机
浏览 181回答 2
2回答

潇湘沐

您可以isset()用于此目的。$imgNames数组包含三个元素,而数组包含$imgs六个元素,您已经遍历了$imgs,这意味着它将运行六次$imgNames,其中某些元素未定义。如果isset()当前函数返回假$files像$imgNames[$files]那么它将被分配一个字符串'no-name'&nbsp; &nbsp; <?php$imgs = array('img 1','img 2','img 3','img 4','img 5','img 6');$imgNames = array('name 1','name 2','name 3',);foreach($imgs as $files => $img){&nbsp; if(!isset($imgNames[$files]))&nbsp; {&nbsp; &nbsp; $imgNames[$files] = 'no-name';&nbsp; }echo 'Image: '.$img.' and Name: '.$imgNames[$files].'<br>';}?>这是演示

一只萌萌小番薯

ImagNames 有3个元素,而另一个数组有5个元素。如果密钥不存在,您可以添加一张不打印的支票foreach($imgs as $files => $img){&nbsp;if(array_key_exists($files,$imgNames){&nbsp; &nbsp;echo 'Image: '.$img.' and Name: '.$imgNames[$files].'<br>';&nbsp;}};
打开App,查看更多内容
随时随地看视频慕课网APP