doubu8643 2019-01-27 08:20 采纳率: 100%
浏览 56
已采纳

使用“array_diff_ukey”比较三个数组的键和值

Can somebody explain, what is 1 and -1 in this code: ($a>$b)?1:-1; ?

I know the Array ( [c] => blue ) is returning because the key c is not exist in $a2 and key_compare_func need to return number smaller, equal or bigger then 0.

But I don't understand, how I get the Array ( [c] => blue ), when the key_compare_func returns 0, 1 and -1:

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

$a1=array("a"=>"red","b"=>"green","c"=>"blue");
$a2=array("a"=>"blue","b"=>"black","e"=>"blue");

$result=array_diff_ukey($a1,$a2,"myfunction");
  • 写回答

3条回答 默认 最新

  • dop83362 2019-01-27 08:33
    关注

    As you can see in array-diff-ukey documentation the "key_compare_func" need to return number smaller, equal or bigger then 0. the numbers 1 and -1 are just example for this results.

    In your case you can simply use strcmp as it return the same logic.

    You have Array ( [c] => blue ) in the return because the key c is not exist in the $a2 array as it say:

    Compares the keys from array1 against the keys from array2 and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values.

    Edited

    Specifically in array-diff-ukey you only need the return 0 because that the way this function is decided the keys are the same so in your example you can define it as:

    function myfunction($a,$b) {
        if ($a === $b)
            return 0;
        return 1; // or -1 or 3 or -3 **just not 0** 
    }
    

    Consider that as the logic behind array-diff-ukey:

    array function array-diff-ukey($a1, $a2, $compareFunction) {
        $arr = array(); // init empty array
        foreach($a1 as $key1 => $value1) { // for each key in a1
            $found = false;
            foreach($a1 as $key2 => $value2) { //search for all keys in a2
                if ($compareFunction($key1, $key2) == 0)
                    $found = true;  // found a key with the same
            }
            if ($found === false) // add the element only if non is found
                $arr[$key1] = $value1; 
        }
        return $arr;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab