multidimensional array difference php

前端 未结 12 1146
离开以前
离开以前 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:08

    Almost a copy of @bernhardh's answer but posting here because my edit was rejected. Uses + instead of array_merge as array_merge will reindex array causing issues with indexed arrays.

    /**
     * Given 2 arrays see what has changed when comparing defaults to the new values.
     *
     * @param array $defaults
     *   Array of default values.
      * @param mixed $new_values
     *   Array of new values.
     *
     * @return array
     *   Nested array strucutre; only the diff.
     */
    function array_diff_multi(array $defaults, $new_values) {
      $result = array();
    
      foreach ($defaults as $key => $val) {
        if (is_array($val) && isset($new_values[$key])) {
          $tmp = array_diff_multi($val, $new_values[$key]);
          if ($tmp) {
            $result[$key] = $tmp;
          }
        }
        elseif (!isset($new_values[$key])) {
          $result[$key] = NULL;
        }
        elseif ($val != $new_values[$key]) {
          $result[$key] = $new_values[$key];
        }
        if (isset($new_values[$key])) {
          unset($new_values[$key]);
        }
      }
    
      $result = $result + $new_values;
      return $result;
    }
    
    0 讨论(0)
  • 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
    0 讨论(0)
  • 2020-12-01 17:09

    For multidimensional arrays, array_diff_assoc works better than array_diff in some cases. I had an issue with array_diff where it was not able to differentiate between 1 or 0 as value ( perhaps some other index had same value ) so array_diff_assoc solved it as it checks for indexes as well. Just for future users who might encounter the same issue.

    0 讨论(0)
  • 2020-12-01 17:11

    Try the function:

    <?php
    $input = ['blue'  => 1, 'white' => ['purple' => 4, 'green' => 3], 'red' => 2];
    $filter = ['blue' => 6, 'white' => ['yellow' => 7, 'green' => 5], 'red' => 2];
    
    /**
     * @param array $input
     * @param array $filter
     * @return array
     */
    function multidimensionalArrayDiffKey(array $input, array $filter)
    {
        if ($diff = array_diff_key($input, $filter)){
            return $diff;
        }else{
            foreach($input as $key => $value){
                if(is_array($value) && $diff = multidimensionalArrayDiffKey($value, $filter[$key])){
                    return [$key => $diff];
                }
            }
        }
        return [];
    }
    print_r(multidimensionalArrayDiffKey($input, $filter));
    

    Result:

    Array
    (
        [white] => Array
            (
                [purple] => 4
            )
    
    )
    
    0 讨论(0)
  • 2020-12-01 17:13

    this solution ah been very helpful to me I hope can help them in something, no matter what the array are in disarray.

    function your_array_diff($arraya, $arrayb) {
    
        foreach ($arraya as $keya => $valuea) {
            if (in_array($valuea, $arrayb)) {
                unset($arraya[$keya]);
            }
        }
        return $arraya;
    }
    
    $a1 = Array
        (
        "0" => Array
            (
            "Empresa" => "TMC01",
            "Paga" => "13/01/2015",
            "ID" => "M2",
            "Valor" => "200",
            "Nombre" => "BONI"
        ),
    
        "1" => Array
            (
            "Empresa" => "TMC01",
            "Paga" => "13/01/2015",
            "ID" => "M1",
            "Valor" => "100",
            "Nombre" => "SUELDO"
        )
    );
    
    $b1 = Array
        (
        "0" => Array
            (
            "Empresa" => "TMC01",
            "Paga" => "13/01/2015",
            "ID" => "M1",
            "Valor" => "100",
            "Nombre" => "SUELDO"
        ),
        "1" => Array
            (
            "Empresa" => "TMC01",
            "Paga" => "13/01/2015",
            "ID" => "M2",
            "Valor" => "200",
            "Nombre" => "BONI"
        )
    );
    
    $resultado = your_array_diff($a1, $b1);
    
    echo "<pre>";
    echo print_r($resultado);
    echo "</pre>";
    
    0 讨论(0)
  • 2020-12-01 17:17

    A better function that works just like the original array_diff.
    Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays recursively.

        <?php
    
        function md_array_diff(array $array1, array $array2, array $_ = null) {
            $diff = [];
            $args = array_slice(func_get_args(), 1);
    
            foreach ($array1 as $key => $value) {
                foreach ($args as $item) {
                    if (is_array($item)) {
                        if (array_key_exists($key, $item)) {
                            if (is_array($value) && is_array($item[$key])) {
                                $tmpDiff = md_array_diff($value, $item[$key]);
    
                                if (!empty($tmpDiff)) {
                                    foreach ($tmpDiff as $tmpKey => $tmpValue) {
                                        if (isset($item[$key][$tmpKey])) {
                                            if (is_array($value[$tmpKey]) && is_array($item[$key][$tmpKey])) {
                                                $newDiff = array_diff($value[$tmpKey], $item[$key][$tmpKey]);
                                            } else if ($value[$tmpKey] !== $item[$key][$tmpKey]) {
                                                $newDiff = $value[$tmpKey];
                                            }
    
                                            if (isset($newDiff)) {
                                                $diff[$key][$tmpKey] = $newDiff;
                                            }
                                        } else {
                                            $diff[$key][$tmpKey] = $tmpDiff;
                                        }
                                    }
                                }
                            } else if ($value !== $item[$key]) {
                                $diff[$key] = $value;
    
                            }
                        } else {
                            $diff[$key] = $value;
                        }
                    }
                }
            }
    
            return $diff;
        }
    
        $arr1 = [
          "A" => [
            "A1" => ['A1-0', 'A1-1', 'A1-2', 'A1-3'],
            "A2" => ['A2-0', 'A2-1', 'A2-2', 'A2-3'],
            "A3" => ['A3-0', 'A3-1', 'A3-2', 'A3-3']
          ],
          "B" => [
            "B1" => ['B1-0', 'B1-1', 'B1-2', 'B1-3'],
            "B2" => ['B2-0', 'B2-1', 'B2-2', 'B2-3'],
            "B3" => ['B3-0', 'B3-1', 'B3-2', 'B3-3']
          ],
          'C' => 123
        ];
    
        $arr2 = [
          "A" => [
            "A1" => ['A1-1', 'A1-2', 'A1-3'],
            "A2" => ['A2-0', 'A2-1', 'A2-2', 'A2-3'],
            "A3" => ['A3-0', 'A3-1', 'A3-2']
          ],
          "B" => [
            "B1" => ['B1-0', 'B1-2', 'B1-3'],
            "B2" => ['B2-0', 'B2-1', 'B2-2', 'B2-3'],
            "B3" => ['B3-0', 'B3-1', 'B3-3']
          ]
        ];
    
        $arr3 = [
          "A" => [
            "A1" => ['A1-0', 'A1-1', 'A1-2', 'A1-3'],
            "A2" => ['A2-0', 'A2-1', 'A2-2', 'A2-3'],
            "A3" => ['A3-0', 'A3-1', 'A3-2']
          ],
          "B" => [
            "B1" => ['B1-0', 'B1-2', 'B1-3'],
            "B2" => ['B2-0', 'B2-1', 'B2-2', 'B2-3'],
            "B3" => ['B3-0', 'B3-1', 'B3-3']
          ]
        ];
    
        $diff = md_array_diff($arr1, $arr2, $arr3);
    
        ?>
        Will Output:
        array (size=3)
          'A' =>
              array (size=2)
                'A1' =>
                  array (size=1)
                    0 => string 'A1-0' (length=4)
                'A3' =>
                  array (size=1)
                    3 => string 'A3-3' (length=4)
          'B' =>
              array (size=2)
                'B1' =>
                  array (size=1)
                    1 => string 'B1-1' (length=4)
                'B3' =>
                  array (size=1)
                    2 => string 'B3-2' (length=4)
          'C' => int 123
    
    0 讨论(0)
提交回复
热议问题