如何避免 PHP 通知“未定义偏移:0”而不检查数组的每个字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7688814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:11:07  来源:igfitidea点击:

How to avoid PHP Notice "Undefined offset: 0" without checking each field of array

phparrays

提问by maze

i have the following array:

我有以下数组:

    $keyvisual_data = array(
        'video_file'            => $row->field_field_video[0]['rendered']['#item']['uri'],
        'bild_file'             => $row->field_field_bild[0]['rendered']['#item']['uri'],
        'subline_src'           => $row->_field_data['nid']['entity']->field_key_titel['und'][0]['safe_value'],
        'screenreader_src'      => $row->field_field_alt_screenreader[0]['rendered']['#markup'],
        'alt_src'               => $row->field_field_bild[0]['rendered']['#item']['alt']
    );

it might happen that some of the fields are not set, this is okay. in fact i am getting this PHP notice:

可能会发生某些字段未设置的情况,这没关系。事实上,我收到了这个 PHP 通知:

Notice: Undefined offset: 0 in bafa_insert_keyvisual() ...........

注意:未定义的偏移量:bafa_insert_keyvisual() 中的 0 .....

is it somehow possible to assign a default value to each key in case it is undefined WITHOUT checking each field of the array manually?

是否有可能以某种方式为每个键分配一个默认值,以防未定义而不手动检查数组的每个字段?

thanks for help

感谢帮助

采纳答案by Dani

Yes, add @before the field like:

是的,@在字段前添加,如:

$keyvisual_data = array(
    'video_file'            => @$row->field_field_video[0]['rendered']['#item']['uri'],
    'bild_file'             => @$row->field_field_bild[0]['rendered']['#item']['uri'],
    'subline_src'           => @$row->_field_data['nid']['entity']->field_key_titel['und'][0]['safe_value'],
    'screenreader_src'      => @$row->field_field_alt_screenreader[0]['rendered']['#markup'],
    'alt_src'               => @$row->field_field_bild[0]['rendered']['#item']['alt']
);

and then initialize the nulls:

然后初始化空值:

if($keyvisual_data['video_file'] === null)
    $keyvisual_data['video_file'] = $default_video_file;

etc...

等等...

回答by Naftali aka Neal

No there is not

不,那里没有

You can do an isset():

你可以做一个isset()

if(isset($array[0])){
    echo $array[0];
}
else {
  //some error?
}

Or if you know that you are only going to be checking index 0:

或者,如果您知道您只会检查索引 0:

$array = $array + array(null);

So if the original $array[0]was unset, now it is null

因此,如果原始$array[0]未设置,现在是null

回答by Luke

You could add a shorthand check if each value is null

如果每个值都为空,您可以添加速记检查

$default_value = "Default value";

$keyvisual_data = array(
        'video_file' => ($row->field_field_video[0]['rendered']['#item']['uri'] == null) ? $default_value : $row->field_field_video[0]['rendered']['#item']['uri']

// etc.. etc...
);

A less messy version of this, to explain the code more clearly:

一个不那么混乱的版本,更清楚地解释代码:

<?php

$default_value = "I am a Default value";

$video_file = null;

$new_array = array(
        'video_file' => ($video_file == null) ? $default_value : $video_file
);

// Will output "I am a Default value"
echo $new_array['video_file'];
?>

回答by Nishu Tayal

You should use "isset" function to check the existence of the field, and infact its a good coding practice..

您应该使用“isset”函数来检查该字段的存在,事实上它是一个很好的编码实践。

$keyvisual_data = array(
      'video_file' => isset($rowWrapper->getVideoFile()) ? $rowWrapper->getVideoFile() : "any default value",
       ...
 );

or you can use it in this way :

或者你可以这样使用它:

if(isset($rowWrapper->getVideoFile()))
{  
     $row['video_file'] = $rowWrapper->getVideoFile();
}
else {
   $row['video_file'] = "";
}

回答by Max

To be honest, the structure of the row data object doesnt seem very convinient and error prone. Especially if you are using $row in some other context, too, I would suggest you wrap it in an object:

老实说,行数据对象的结构似乎不太方便且容易出错。特别是如果您也在其他一些上下文中使用 $row ,我建议您将它包装在一个对象中:

class RowWrapper
{
    private $_row;

    public function __construct($row)
    {
        $this->_row = $row;
    }

    public function getVideoFile()
    {
        if (!isset($row->field_field_video[0])) {
            return null;
        }

        return $row->field_field_video[0]['rendered']['#item']['uri'];
    }

    ...
}

$rowWrapper = new RowWrapper($row);

$keyvisual_data = array(
    'video_file'            => $rowWrapper->getVideoFile(),
    ...
);

If you there is only one value e. g. inside of $row->field_field_videothen it shouldnt be an array. I would use a wrapper class as a kind of anti corruption layer if that strange datastructure comes from a remote source or the like. Otherwise it will creep through your while application with $row->field_field_video[0]...stuff all over the place.

如果你只有一个值,例如里面,$row->field_field_video那么它不应该是一个数组。如果那个奇怪的数据结构来自远程源等,我会使用包装类作为一种反腐败层。否则它会在你的 while 应用程序$row->field_field_video[0]...中到处都是东西。

I know this is not the fast and easy solution you want, but swallowing errors is never a good idea.

我知道这不是您想要的快速简便的解决方案,但吞下错误绝不是一个好主意。