PHP - Mutidimensional array diff

前端 未结 3 1101
忘掉有多难
忘掉有多难 2021-01-14 20:43

i would like to ask for your help since I\'m having difficulty resolving this matter. I had created a function to facilitate on array diff but it does not suffice to my need

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-14 21:26

    You want something more or less like this:

    public function array_diff_multidimensional($arr1, $arr2) {
        $answer = array();
        foreach($arr1 as $k1 => $v1) {
            // is the key present in the second array?
            if (!array_key_exists($k1, $arr2)) {
               $answer[$k1] = $v1; 
               continue;
            }
    
            // PHP makes all arrays into string "Array", so if both items
            // are arrays, recursively test them before the string check
            if (is_array($v1) && is_array($arr2[$k1])) {
                $answer[$k1] = array_diff_multidimensional($v1, $arr2[$k1]);
                continue;
            }
    
            // do the array_diff string check
            if ((string)$arr1[$k1] === (string)$arr2[$k1]) {
                continue;
            }
    
            // since both values are not arrays, and they don't match,
            // simply add the $arr1 value to match the behavior of array_diff
            // in the PHP core
            $answer[$k1] = $v1;
        }
    
        // done!
        return $answer;
    }
    

提交回复
热议问题