PHP:array_uintersect()意外输入参数

问题描述 投票:0回答:1

最近碰到了功能array_uintersect。只是想知道是否有任何人可以解释输入参数是如何传递的,因为我得到了传递给回调函数的意外输入,我已经通过This回答但是找不到我的问题的答案。任何帮助或线索将不胜感激,只是想了解回叫功能的工作。

注意:功能的结果是完美的。

码:

function myfunction($a,$b) {
    echo "$a -- $b \n";
    if ($a===$b) {
        return 0;
    }
    return ($a>$b)?1:-1;
}

$a1 = array(1,2,3);
$a2 = array(4,5,1);
$result = array_uintersect($a1,$a2,"myfunction");
print_r($result);

当我们将这两个数组作为参数传递时,期望输入是来自每个数组的值,其中得到的结果如下。

结果:

1 -- 2
2 -- 3
4 -- 5
5 -- 1
4 -- 1
1 -- 1
1 -- 2
2 -- 4
3 -- 4
Array ( [0] => 1 )
php arrays callback
1个回答
1
投票

正如@Nick在他的评论中提到的(以及你分享的链接)声称array_uintersect在检查交叉之前对数组进行排序。

这将是以下部分:

1 -- 2 // sort first array
2 -- 3 // sort first array
4 -- 5 // sort second array
5 -- 1 // sort second array
4 -- 1 // sort second array

现在两个数组都是:$a1 = [1,2,3] and $a2 = [1,4,5]

现在的交叉部分:

1 -- 1  // checking index 0 in both array
1 -- 2  // checking $a2[0] and $a1[1] -> 2 is bigger so let continue with him
2 -- 4  // checking $a1[1] and $a2[1] -> as we already check $a2[0] -> 4 is bigger so continue with him
3 -- 4  // checking $a1[2] and $a2[1] -> 4 is bigger but not $a1[3] so done checking 

注意交叉点可以在O(n)be中完成,因为之前完成的排序...

© www.soinside.com 2019 - 2024. All rights reserved.