在PHP中获取未定义的偏移量0在电子邮件中未使用附件

时间:2015-07-21 12:35:47

标签: php yii

这里使用此代码进行电子邮件发送,它在添加附件时工作正常,但在发送没有附件的邮件时,收到错误

  

未定义的偏移量0

mycode的

if($model->attachment) 
                {
                    $message = Yii::$app->mailer->compose()
                    ->setFrom([ Yii::$app->user->identity->email => 'Fiducial Insurance'])
                    ->setTo($model->email)
                    ->setSubject($model->subject)
                    ->setHtmlBody($model->content);

                    foreach ($model->attachment as $file) 
                    {
                        $file->saveAs('emailattachments/' .$file->baseName. '.' . $file->extension);
                        $filename = 'emailattachments/' .$file->baseName. '.' . $file->extension;
                        $message->attach($filename);
                    }

                    $columns = array_map(function($column) {
                        return 'emailattachments/' . $column;
                    }, $model->attachment);
                    $model->attachment = implode(', ', $columns);

                    $message->send();

                }
                else
                {
                    $message = Yii::$app->mailer->compose()
                    ->setFrom([ Yii::$app->user->identity->email => 'Fiducial Insurance'])
                    ->setTo($model->email)
                    ->setSubject($model->subject)
                    ->setHtmlBody($model->content)
                    ->send();
                }
                $model->save();

如何解决此错误

1 个答案:

答案 0 :(得分:0)

您可以在if中包含添加附件的行,只有在至少有一个附件时才会执行。

                //...
                $hasAttachment = false;
                foreach ($model->attachment as $file) 
                {
                    $hasAttachment = true;
                    $file->saveAs('emailattachments/' .$file->baseName. '.' . $file->extension);
                    $filename = 'emailattachments/' .$file->baseName. '.' . $file->extension;
                    $message->attach($filename);
                }

                if($hasAttachment) {
                    $columns = array_map(function($column) {
                        return 'emailattachments/' . $column;
                    }, $model->attachment);
                    $model->attachment = implode(', ', $columns);
                }
                //...

请尝试计算($ model->附件)也可以。上述方法更像是一种解决方法。

为什么会这样?

$model->attachment == array() == true

http://php.net/manual/en/language.types.boolean.php

这意味着即使数组为空,也会进入该代码块。如果变量未定义,您将无法进入代码块,您可以使用unset($model->attachment)模拟