Multidimensional array diff

前端 未结 3 448
太阳男子
太阳男子 2021-01-22 05:39

I got 2 arrays:

$big_array = array (
                    array (
                            array (
                                      \'correct\' => FALS         


        
3条回答
  •  鱼传尺愫
    2021-01-22 06:33

    I just edited the function from Murali Kumar cause I needed one more information. It will check if the arrays are the same size and contains the same values.

    function arrayRecursiveDiff($aArray1, $aArray2) {
        if(count($aArray1) > count($aArray2)) {
            $small_arr = $aArray2;
            $big_arr = $aArray1;
            $arr1_is_big = 1;
            $arr2_is_big = 0;
        } elseif(count($aArray1) < count($aArray2)) {
            $small_arr = $aArray1;
            $big_arr = $aArray2;
            $arr1_is_big = 0;
            $arr2_is_big = 1;
        } else {
            $small_arr = $aArray1;
            $big_arr = $aArray2;
            $arr1_is_big = 0;
            $arr2_is_big = 0;
        }
        $aReturn = array();
    
        foreach($big_arr as $mKey => $mValue) {
            if(array_key_exists($mKey, $small_arr)) {
                if(is_array($mValue)) {
                    $aRecursiveDiff = arrayRecursiveDiff($mValue, $small_arr[$mKey]);
                    if(count($aRecursiveDiff)) {
                        $aReturn[$mKey] = $aRecursiveDiff;
                    }
                } else {
                    if($mValue != $small_arr[$mKey]) {
                        $aReturn[$mKey] = $mValue;
                    }
                }
            } else {
                $aReturn[$mKey] = $mValue;
            }
        }
        if($arr1_is_big)
            $aReturn["arr1_is_big"] = $arr1_is_big;
    
        if($arr2_is_big)
            $aReturn["arr2_is_big"] = $arr2_is_big;
    
        return ($aReturn);
    }
    

提交回复
热议问题