String as Array将在接受为数组的函数中发送的值

时间:2015-09-16 06:57:31

标签: php arrays

我有一个名为validate()的方法,它接受数组作为参数。

E.g。

$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()方法创建动态数组值?

2 个答案:

答案 0 :(得分:2)

您可以使用array_merge

$v->validate(array_merge(
    [
      'username' => [$username, 'required'],
      'email'    => [$email, 'required'],
      'password' => [$password, 'required']
    ],
    $validate_parameters
));

答案 1 :(得分:2)

我不确定你要完成什么,但也许是这样的:它分别创建两个数组,然后合并它们

$staticFields = [
    'username' => [$username, 'required'],
    'email'    => [$email, 'required'],
    'password' => [$password, 'required']
];

//this can be assigned with your DynamicFields function
$dynamicFields =  [
    'dynamicfield_1' => ['value_1', 'rule_1'],
    'dynamicfield_2' => ['value_2', 'rule_2'],
    'dynamicfield_3' => ['value_3', 'rule_3']
];

//merge both arrays, and pass them
$v->validate(array_merge($staticFields, $dynamicFields));