phparraysmultidimensional-arrayfilterarray-difference

Find associative row differences between two 2d arrays with the same number of rows


How can I compare multidimensional associative arrays?

I'm looking for some function like: http://www.php.net/manual/en/function.array-diff.php#98680

I want to compare two 2d arrays (row-by-row) and show the associative element differences.

$array1 = [
    ['item' => '39.00', 'time' => '0.00'],
    ['item' => '49.00'],
    ['time' => '0.00', 'Value' => 0],
    ['item' => '49.00', 'time' => '0.00']
];

$array2 = [
    ['item' => '39.00', 'time' => '10.00'],
    ['item' => '49.00'],
    ['time' => '0.00', 'Value' => 0],
    ['item' => '49.00', 'time' => '0.00', 'Value' => 3]
];

Desired output showing differences in both directions:

[
    0 => ['time' => 10.00],  // the different time value from array2
    3 => ['Value' => 3]      // array2 element not even a key in array1
]

Solution

  • This should get you most of the way there:

    $arrayDiff = array_map('array_diff_assoc', $array1, $array2);
    

    Maybe follow that with array_filter($arrayDiff) if you want to get rid of the empty (equal) elements.

    After removing empty rows, $arrayDiff will contain:

    array (
      0 => 
      array (
        'time' => '0.00',
      ),
    )