我想知道是否可以搜索具有其他数组值的数组。因此,如果有2个数组,则数组a和数组b - 数组a将查看其值是否为数组b中的任何结果。
define('L001', 'Wrong Password');
define('L002', 'Form not filled in');
define('L003', 'Account is not active');
$errors = array ('L001', 'L002', 'L003');
$args = explode('/', rtrim($_SERVER['QUERY_STRING'], '/'));
if (isset($args) && in_array($errors, $args)) {
if (in_array($errors[0], $args)) {
$error = L001;
} elseif (in_array($errors[1], $args)) {
$error = L002;
} elseif (in_array($errors[2], $args)) {
$error = L003;
}
} else {
//no errors
}
这样的事情可能吗?
答案 0 :(得分:0)
上面的代码在我脑海中不起作用。此外,in_array()仅适用于整个数组,而不是一个元素。更明智的是:
$errors = array('L001' => 'Wrong Password',
'L002' => 'Form not filled in',
'L003' => 'Account is not active');
if(isset($args) && in_array($args, $errors)) {
echo $errors[$args]; // will output the text
} else {
// no errors
}
您可以选择将$ errors [$ args]分配给变量以供以后使用,如果您不想在那里输出它然后使用$error = $errors[$args];
答案 1 :(得分:0)
我建议array_intersect()
或array_intersect_key()
,具体取决于您设置静态$errors
数组的方式。
代码:
$errors = array ('L001'=>'Wrong Password', 'L002'=>'Form not filled in', 'L003'=>'Account is not active');
$QS='L002/L003/L005/'; // some test querystring data
$args = explode('/', rtrim($QS,'/'));
$found_errors=array_intersect_key($errors,array_flip($args)); // no need to check isset() on $args
var_export($found_errors);
echo "\n\n";
// or if you just want the first one:
echo current($found_errors);
输出:
array (
'L002' => 'Form not filled in',
'L003' => 'Account is not active',
)
Form not filled in