gpt4 book ai didi

php - 循环遍历错误消息包,然后创建一个新数组

转载 作者:行者123 更新时间:2023-12-04 02:11:22 26 4
gpt4 key购买 nike

我正在尝试遍历错误消息包 ($validator->errors()->getMessages()) 数组并将其对象推送到另一个数组 ($error)

$error = array();
$validator = Validator::make($request->all(),[
'username' => 'required|unique:User',
'password' => 'required',
'fullname' => 'required|unique:Profile',
'email' => 'required|email|unique:Profile'
]);

if($validator->fails()) :
foreach($validator->errors()->getMessages() as $m => $key):
array_push($error,$key);
endforeach;
endif;

然后循环到新数组($error)并基于新数组对象($str)创建一个字符串
$str = '<ul class="c_red padding_zero margin_zero menu">';
foreach($error as $e ){ // this is the line 113
$str.= '<li>'.$e.'</li>';
}
$str.='</ul>';

return array('success' => false, 'message' => $error );

但它返回一个错误

Array to string conversion line 113



这是不循环到 $error 数组以创建 $str 字符串时的响应

{"success":false,"message":[["The username field is required."],["The password > field is required."],["The fullname field is required."],["The email field is > required."]]}

最佳答案

错误中的每个键可能包含多个错误,因此它将是一个字符串...

所以你可以这样做:

if($validator->fails()) :
foreach($validator->errors()->getMessages() as $validationErrors):
if (is_array($validationErrors)) {
foreach($validationErrors as $validationError):
$error[] = $validationError;
endforeach;
} else {
$error[] = $validationErrors;
}
endforeach;
endif;

在这里,您将获得所有错误消息的数组...

关于php - 循环遍历错误消息包,然后创建一个新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37906455/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com