multidimensional array difference php

前端 未结 12 1168
离开以前
离开以前 2020-12-01 17:05

I have two multidimensional arrays and I want the difference. For eg. I have taken two-dimensional two arrays below

$array1 = Array (
       [a1] => Array         


        
12条回答
  •  日久生厌
    2020-12-01 17:09

    I know this thread is kind of old, however I ran into a few problems with the original solution. So here is my solution of the problem.

    private function array_diff_recursive($array1, $array2){
        $result = [];
        foreach($array1 as $key => $val) {
            if(array_key_exists($key, $array2)){
                if(is_array($val) || is_array($array2[$key])) {
                    if (false === is_array($val) || false === is_array($array2[$key])) {
                        $result[$key] = $val;
                    } else {
                        $result[$key] = $this->array_diff_recursive($val, $array2[$key]);
                        if (sizeof($result[$key]) === 0) {
                            unset($result[$key]);
                        }
                    }
                }
            } else {
                $result[$key] = $val;
            }
        }
        return $result;
    }
    

    Problems Encountered / Fixed

    1. Result populates with keys that have no difference
    2. If one value is an array and the other is not, it doesn't consider it a difference

提交回复
热议问题