为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
繁华开满天机 2021-05-02 16:34:40
我正在尝试显示存储在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 1Image: img 2 and Name: name 2Image: img 3 and Name: name 3Image: img 4 and Name: no-nameImage: img 5 and Name: no-nameImage: img 6 and Name: no-name但实际输出是:Image: img 1 and Name: name 1Image: img 2 and Name: name 2Image: img 3 and Name: name 3Notice: 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: 如何解决此问题以显示默认的“无名称”字符串?
查看完整描述

2 回答

?
潇湘沐

TA贡献1816条经验 获得超6个赞

您可以isset()用于此目的。$imgNames数组包含三个元素,而数组包含$imgs六个元素,您已经遍历了$imgs,这意味着它将运行六次$imgNames,其中某些元素未定义。如果isset()当前函数返回假$files像$imgNames[$files]那么它将被分配一个字符串'no-name'


    <?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)

{

  if(!isset($imgNames[$files]))

  {

    $imgNames[$files] = 'no-name';

  }

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

}

?>

这是演示


查看完整回答
反对 回复 2021-05-07
?
一只萌萌小番薯

TA贡献1795条经验 获得超7个赞

ImagNames 有3个元素,而另一个数组有5个元素。


如果密钥不存在,您可以添加一张不打印的支票


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

{


 if(array_key_exists($files,$imgNames){


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

 }

};


查看完整回答
反对 回复 2021-05-07
  • 2 回答
  • 0 关注
  • 180 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信