【问题标题】:Notice: Undefined offset: different rows注意:未定义的偏移量:不同的行
【发布时间】:2019-04-21 09:55:39
【问题描述】:

我正在尝试显示存储在 2 个数组中的图像元数据...
当图像没有名称时,我想显示“无名称”。以下是我现在的显示方式:

$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: 

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

【问题讨论】:

  • 感谢纠正@YakovL
  • 不客气。查看您的其他问题,我建议您在制定这些问题上投入更多精力:这将帮助您获得(更多,更好)答案

标签: php arrays foreach


【解决方案1】:

您可以为此目的使用isset()$imgNames 数组包含三个元素,而 $imgs 包含六个元素,您已经循环了 $imgs,这意味着它将运行六次,而 $imgNames 的某些元素未定义。如果isset() 函数对当前$files$imgNames[$files] 一样返回false,那么它将被分配一个字符串'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>';
}
?>

这里是demo

【讨论】:

    【解决方案2】:

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

    如果密钥不存在,您可以添加一个检查以不打印它

    foreach($imgs as $files => $img)
    {
    
     if(array_key_exists($files,$imgNames){
    
       echo 'Image: '.$img.' and Name: '.$imgNames[$files].'<br>';
     }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      • 2023-03-27
      • 2012-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多