为什么我会收到错误&#39;非法偏移类型&#39;在此代码中的$errors[$field] .= '<div class="error"><p>' . $error . '</p></div>';
行?
代码:
$errors = [];
foreach ($validation->errors() as $field)
{
$errors[$field] = '';
foreach ($field as $error) {
$errors[$field] .= '<div class="error"><p>' . $error . '</p></div>';
}
}
验证:
private function addError($field, $error)
{
$this->errors[$field][] = $error;
}
public function errors()
{
return $this->errors;
}
解决方案:
foreach ($validation->errors() as $key => $fieldErrors)
{
$errors[$key] = '';
foreach ($fieldErrors as $error) {
$errors[$key] .= '<div class="error"><p>' . $error . '</p></div>';
}
}
答案 0 :(得分:3)
foreach ($field as $error)
这一行表明$field
是一个数组。您不能将数组用作另一个数组的键。
$errors[$field] << won't work!
要解决此问题,请将addError
方法更改为:
private function addError($field, $error)
{
$this->errors[$field] .= $error; //I changed [$field][] to [$field]
}