如何根据条件从两个数组创建一个数组

时间:2015-01-15 06:58:12

标签: php arrays

我有两个数组:

$generated_errors = array(
          'required'  => 'fieldname', 
          'min'  => 'fieldname', 
          'max'  => 'fieldname');
$all_errors = array(
          'required' => ' is required', 
          'min' => ' must be at least 6 character', 
          'max' => ' must be at maximum 20 character', 
          'onlynumber' => ' must be only numbers', 
          'email' => ' must be valid email');

我希望他们两个中的1个数组(根据$generated_errors):

$errors = array(
          'required' => 'Field name is required', 
          'min' => 'Field name must be at least 6 character', 
          'max' => 'Field name must be maximum 20 character');

3 个答案:

答案 0 :(得分:1)

您可以迭代$generated_errors并使用$all_errors值进行丰富:

for ($generated_erros as $key => $value) {
    $erros[$key] = $value . $all_errors[$key];
}

答案 1 :(得分:0)

你应该这样做

$errors =array();
for ($generated_erros as $key => $value) {
    $errors[$key] = $value . $all_errors[$key];
}

答案 2 :(得分:0)

最好这样做:

$result = array();
array_walk($generated_errors, function($item, $value) use(&$all_errors, &$result){
       array_push($result, [$key => ($generated_errors[$key] . $all_errors[$key])]);
});

我还没有测试过上面的代码,但我认为它有效。我想它比for loop快。因为在for loop中有很多降低速度会降低速度(尽管不是很多)。