用消息替换数组中的匹配值

时间:2022-09-25 08:02:37

An example of what my validator (in my controller) is returning is the following array with error codes:

我的验证器(在我的控制器中)返回的示例是以下带有错误代码的数组:

Array
(
    [name] => Array
        (
            [0] => Required
            [1] => Alpha
            [2] => NoSpace
        )

    [terms] => Array
        (
            [0] => Required
        )
)

And in my View (UI logic) I want to replace every matching error code with sentence in this array:

在我的视图(UI逻辑)中,我想用这个数组中的句子替换每个匹配的错误代码:

$messages = array(
    'name' => array(
        'Required' => 'You did not enter your first name.',
        'MaxChars' => 'Your first name cannot be longer then 35 characters.',
        'Alpha'    => 'Your first name must contain only alpha characters.'
    ),
    'terms' => array(
        'Required' => 'You must agree to our policies.'
    )
);

And if there is no match, I want to just keep the current value it already has.

如果没有匹配,我想保持它已经拥有的当前值。

So in this case, NoSpace error code would stay NoSpace (because no match), but for the other error codes they would be replaced with the corresponding message.

因此,在这种情况下,NoSpace错误代码将保留NoSpace(因为没有匹配),但对于其他错误代码,它们将被替换为相应的消息。

How could I achieve this?

我怎么能实现这个目标?

1 个解决方案

#1


1  

Something like this should work

这样的事情应该有效

<?php

foreach ($arr as $k => $v) {
   for ($i=0, $c = count($v); $i<$c; ++$i) {
      if (isset($messages[$k][$v[$i]])) {
           $arr[$k][$i] = $messages[$k][$v[$i]];
      }
   }
}

#1


1  

Something like this should work

这样的事情应该有效

<?php

foreach ($arr as $k => $v) {
   for ($i=0, $c = count($v); $i<$c; ++$i) {
      if (isset($messages[$k][$v[$i]])) {
           $arr[$k][$i] = $messages[$k][$v[$i]];
      }
   }
}