1

Here's the code, it's very simple:

<?php
$tab = array (
    (object)array( 'id' => 1,),
    (object)array( 'id' => 4,),
    (object)array( 'id' => 12,),
    (object)array( 'id' => 22,),
    (object)array( 'id' => 25,),
);

$tab_json = array (
    (object)array( 'id' => 1,),
    (object)array( 'id' => 4,),
    (object)array( 'id' => 12,),
    (object)array( 'id' => 22,),
    (object)array( 'id' => 25,),
    (object)array( 'id' => 2,),
);
$difference = array_udiff($tab_json, $tab, function($a, $b) {
    echo $a->id." <-> ".$b->id."\n";
    return (count(array_diff_assoc(get_object_vars($a), get_object_vars($b))))>0;
});
?>

Here's the output:

12 <-> 4
12 <-> 1
12 <-> 22
12 <-> 25
2 <-> 12
4 <-> 25
4 <-> 1
22 <-> 4
25 <-> 1
12 <-> 4
12 <-> 1
12 <-> 22
25 <-> 12
4 <-> 22
1 <-> 4
1 <-> 22
1 <-> 4
1 <-> 1
1 <-> 25
25 <-> 4
25 <-> 1
25 <-> 12
25 <-> 25
25 <-> 4
4 <-> 1
4 <-> 12
4 <-> 25
4 <-> 22
22 <-> 1
22 <-> 12
22 <-> 25
22 <-> 12
12 <-> 1
12 <-> 12
12 <-> 2
2 <-> 12
2 <-> 25

I don't understand how it's computed: look at 12: it's compared more than 10 times (whereas, from what I understand, it should be compared no more than the number of elements of the second array), and moreover it's compared three times with 1!

Tested on:

PHP 5.3.9
PHP 5.3.2-1ubuntu4.14
4

1 回答 1

0

实际产生结果的方式array_udiff()当然是一个实现细节,可能会发生变化。所以虽然我说的现在可能是真的,但你不能依赖它。

例如,如果您需要使用旧版本的 PHP,您可能会很好地实现该函数的兼容版本,它只是将第一个数组的每个元素与第二个数组的每个元素进行比较,丢弃任何匹配项。

另一方面,如果您想要最高性能,您可以快速排序第二个数组的元素,然后对第一个数组的元素执行二进制搜索。

PHP 5.3 似乎结合了快速排序和线性搜索。但是,一旦找到更大的元素,它就会中止搜索。

于 2012-04-22T20:30:06.370 回答