我知道PHP有许多数组函数,但我不确定使用哪一个,或者是否需要自定义函数。
我有一个接受数组的函数,我需要那些作为参数传递的数组才能拥有某些键。传递数组时,我需要检查数组的形式是否正确,例如:
<?php function( $array ) {
// Array needs to have form Array('server'=>, 'database'=>,'username'=>
I could check it as "array_key_exists", but it seems too long, there must be a
a way to iterate throught arguments
$template = Array('server'=>'', 'database'=>'','username'=>'');
foreach( $array AS $key => $value ) {
//Somehow compare if array $array includes keys as $template
有没有办法做到这一点?非常感谢你。
答案 0 :(得分:3)
$template = array('server', 'database', 'username');
if (array_intersect_key($template, array_keys($array)) == $template) {
// all parameters were passed
}
$template = array('server', 'database', 'username');
if (empty(array_diff($template, array_keys($array)))) {
// all parameters got passed
}
对于PHP&lt; 5.5.0:用count(array_diff($template, $array)) == 0
答案 1 :(得分:0)
if(array_intersect( array_keys($array), array_keys($template)) == array_keys($template)){
// do your business
}
答案 2 :(得分:0)
function check_keys(array $array) {
$template = array('server', 'database', 'username');
return (count(array_diff($template, array_keys($array))) == 0);
}