Skip to content

Instantly share code, notes, and snippets.

@gajus
Created September 30, 2013 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gajus/271ad5f36337a32a184c to your computer and use it in GitHub Desktop.
Save gajus/271ad5f36337a32a184c to your computer and use it in GitHub Desktop.
<?php
header('Content-Type: text-plain');
$value_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, $value_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, $value_compare_func);
echo PHP_EOL;
var_dump($subject);
/**
* @author Gajus Kuizinas <gk@anuary.com>
* @version 1.0.0 (2013 09 30)
*/
function _array_intersect_ukey (array $arr1, array $arr2, $value_compare_func) {
$arr_matched = [];
$arr_unmatched = [];
$args = func_get_args();
$value_compare_func = end($args);
foreach ($arr1 as $k1 => $v1) {
foreach ($arr2 as $k2 => $v2) {
$diff = $value_compare_func($k1, $k2);
//var_dump('k1=' . $k1 . ', k2=' . $k2 . ', diff=' . $diff);
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));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment