源码:
<?php
$i = 1;
function key_compare_func($a, $b)
{
global $i;
var_dump($a);
var_dump($b);
echo "=====$i".PHP_EOL;
if ($a === $b) {
return 0;
}
$i += 1;
return ($a > $b)? 1:-1;
}
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_uassoc($array1, $array2, "key_compare_func");
print_r($result);
结果:
string(1) "b"
string(1) "a"
=====1
string(1) "b"
string(1) "c"
=====2
int(0)
string(1) "b"
=====3
string(1) "a"
int(0)
=====4
int(0)
string(1) "a"
=====5
int(1)
int(0)
=====6
string(1) "a"
int(0)
=====7
string(1) "a"
string(1) "a"
=====8
int(0)
string(1) "a"
=====8
int(0)
int(0)
=====9
string(1) "b"
string(1) "a"
=====9
string(1) "b"
int(0)
=====10
string(1) "b"
int(1)
=====11
string(1) "c"
string(1) "a"
=====12
string(1) "c"
int(0)
=====13
string(1) "c"
int(1)
=====14
Array
(
[b] => brown
[c] => blue
[0] => red
)
请问:
对于这个函数,他的比较原理是什么?为什么要进行14次比较?
ringa_lee2017-04-10 17:01:01
查阅了一下源码,在比较之前,PHP还进行了一次排序操作,排序时也会采用这个回调函数,这也就是你会看到结果中会有b
和c
这两个出现在同一个数组中的键进行比较的记录。