如果 $key_compare_func 使用正则表达式进行比较,则 "array_intersect_ukey" 将无法正常工作。"_array_intersect_ukey" 完全实现了 "array_intersect_ukey" 接口,并正确地处理布尔比较。但是,出于效率原因,应优先使用本机实现。
<?php
$key_compare_func = function ($a, $b) {
var_dump('a=' . $a. '; b=' . $b);
if (strpos($b, '/') === 0) {
return preg_match($b, $a) > 0 ? 0 : -1;
}
if ($a == $b) {
$weight = 0;
} else if ($a > $b) {
$weight = 1;
} else {
$weight = -1;
}
var_dump('literal comparison: ' . $weight);
return $weight;
};
$foo = ['aab' => '', 'bbb' => '', 'ccb' => '', 'abb' => ''];
$bar = ['/[a-z]b[a-z]/' => ''];
$buz = ['/c[a-z][a-z]/' => ''];
echo PHP_EOL . 'array_intersect_ukey' . PHP_EOL . PHP_EOL;
$subject = array_intersect_ukey ($foo, $bar, $buz, $key_compare_func);
echo PHP_EOL;
var_dump($subject);
echo PHP_EOL . '_array_intersect_ukey' . PHP_EOL . PHP_EOL;
$subject = _array_intersect_ukey($foo, $bar, $buz, $key_compare_func);
echo PHP_EOL;
function _array_intersect_ukey (array $arr1, array $arr2, $key_compare_func) {
$arr_matched = [];
$arr_unmatched = [];
$args = func_get_args();
$key_compare_func = end($args);
foreach ($arr1 as $k1 => $v1) {
foreach ($arr2 as $k2 => $v2) {
$diff = $key_compare_func($k1, $k2);
if ($diff === 0) {
$arr_matched[$k1] = $v1;
} else {
$arr_unmatched[$k1] = $v1;
}
}
}
if (count($args) <= 3) {
return $arr_matched;
}
array_splice($args, 0, 2, [$arr_unmatched]);
return array_merge($arr_matched, call_user_func_array('_array_intersect_ukey', $args));
}
?>