duandu5846 2016-10-12 15:09
浏览 66
已采纳

无论顺序如何,检查关联的多维数组是否相等

The two arrays are considered equal since they have the same 1st dimension indexes (Electric, Gas, Water) the same 2nd dimension indexes (Gym, Library), and the same values for each intersect. The values will always be literals and not arrays or objects. Order doesn't mater.

How can PHP verify that they are equal based on the above definition of equality?

Array
(
    [Electric] => Array
        (
            [Gym] => 24
            [Library] => 25
        )

    [Gas] => Array
        (
            [Gym] => 13
            [Library] => 
        )

    [Water] => Array
        (
            [Gym] => 
            [Library] => 
        )

)
Array
(
    [Gas] => Array
        (
            [Library] => 
            [Gym] => 13
        )

    [Electric] => Array
        (
            [Gym] => 24
            [Library] => 25
        )

    [Water] => Array
        (
            [Library] => 
            [Gym] => 
        )

)

EDIT. My attempt is as follows...

if(count($arr1) != count($arr2) || array_diff($arr1, $arr2) !== array_diff($arr2, $arr1)) {
  $error='Values do not match.';
}
  • 写回答

5条回答 默认 最新

  • dousuize3082 2016-10-12 15:42
    关注

    Here's a recursive comparison function

    function CompareRecursive($array1, $array2, &$mismatches) {
        foreach ($array1 as $key => $value) {
            if (!isset($array2[$key])) { 
                $mismatches[$key] = [ $value ];
                continue;
            } 
    
            $value2 = $array2[$key];  
            if (!is_array($value) || !is_array($value2)) {                
                if ($value != $value2) {
                    $mismatches[$key] = [
                        $value, $value2
                    ];
                }
            } else {
                $mismatches_internal = [];
                CompareRecursive($value, $value2, $mismatches_internal);
                if (!empty($mismatches_internal)) {
                    $mismatches[$key] = $mismatches_internal;
                }
            } 
        }
        return empty($mismatches);
    }
    

    As an added bonus this keeps track of mismatched entries too, there's a drawback when using this method that it won't work if $array2 has extra elements that $array1 doesn't but you can resolve this by doing:

    $isEqual = CompareRecursive($array1,$array2) && CompareRecursive($array2,$array1);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办