作者:做条温顺的鱼_169 | 来源:互联网 | 2024-11-02 14:01
我有一个称为validate()的方法,该方法接受数组作为参数.例如.$v->validate([ 'username' => [$username, 'required'], 'emai
我有一个称为validate()的方法,该方法接受数组作为参数.
例如.
$v->validate([
'username' => [$username, 'required'],
'email' => [$email, 'required'],
'password' => [$password, 'required'],
]);
所以我要做的是为此动态创建参数.虽然不知道正确的术语.例如!
$v->validate([
'username' => [$username, 'required'],
'email' => [$email, 'required'],
'password' => [$password, 'required'],
$validate_parameters
]);
像这样的东西,会有固定字段和其他动态字段将作为参数发送.它将翻译为:
$v->validate([
'username' => [$username, 'required'],
'email' => [$email, 'required'],
'password' => [$password, 'required'],
'dynamicfield_1' => ['value_1', 'rule_1'],
'dynamicfield_2' => ['value_2', 'rule_2'],
'dynamicfield_3' => ['value_3', 'rule_3'],
]);
这是我的方法.
public function validateDynamicFields($compressed_field, $rules) {
$parameters = '';
foreach ($compressed_field as $key => $value) {
// Well technically this will not work since it's not even an array or some sort.
$parameters .= $key => [$value, $rules];
// I even tried this and hope that it would work but it doesn't
// $parameters .= "'{$key}' => [{$value}, '{$rules}'],";
}
return $parameters;
}
问题是,如何为validate()方法动态创建数组值?
解决方法:
您可以使用array_merge:
$v->validate(array_merge(
[
'username' => [$username, 'required'],
'email' => [$email, 'required'],
'password' => [$password, 'required']
],
$validate_parameters
));