dongna9185 2015-01-12 21:16
浏览 14
已采纳

我如何检查具有相似订单的数组中key =>值配对差异的数量?

For example, if I have two arrays:

$array1 = array('a', 'b', 'c', 'd');

$array2 = array('a', 'c', 'b', 'd');

Assuming that both arrays have similar orders (based on the last and first values), how would I check to see that are two differences in their key value pairings, in their defined orders?

As well as this, how could I return (possibly through another function), where exactly these differences are, by key?

  • 写回答

1条回答 默认 最新

  • douke8473 2015-01-12 21:31
    关注

    Using array_diff_assoc() with a callback will give you a result of the difference but only with the first arrays keys and values returned. If you want the second arrays differences, reverse the order of the parameters

    $array1 = array('a', 'b', 'c', 'd');
    
    $array2 = array('a', 'c', 'b', 'd');
    
    function key_compare ($a, $b) {
        if ($a === $b) {
            return 0;
        }
        return ($a > $b)? 1:-1;
    })
    
    print_r(array_diff_uassoc($array1,$array2, "key_compare");
    

    Result... Array ( [1] => b [2] => c )

    Reversed...

    print_r(array_diff_uassoc($array2,$array1, "key_compare");
    

    Result... Array ( [1] => c [2] => b )

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题