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

后端 未结 5 1162
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-05 03:27

i have the following array:

    $keyvisual_data = array(
        \'video_file\'            => $row->field_field_video[0][\'rendered\'][\'#item\'][\'uri\'],         


        
5条回答
  •  礼貌的吻别
    2021-02-05 03:40

    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:

    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_video then 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.

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

提交回复
热议问题