saudsaad saudsaad - 4 months ago 11
PHP Question

Return the difference of multi-dimensional arrays

how can I compare these two arrays?

I want the result be elements that are not available in one array. For example:

Array #1

Array
(
[0] => Array
(
[0] => a
[1] => 1
)

[1] => Array
(
[0] => b
[1] => 2
)

[2] => Array
(
[0] => c
[1] => 3
)
)


Array #2

Array
(
[0] => Array
(
[0] => a
[1] => 1
)

[1] => Array
(
[0] => b
[1] => 2
)
)


Result

Array
(
[0] => Array
(
[0] => c
[1] => 3
)
)

Answer

You can write a custom function since there's no in-built function for multi-dimension arrays.

Try this:

$array1 = array(
   array ('a', 1),
   array ('b', 2),
   array ('c', 3)
 );

 $array2 = array(
   array ('a', 1),
   array ('b', 2)
 );

function array_diff_assoc_recursive($array1, $array2) {

   $difference = NULL;
   foreach($array1 as $key => $value) {
      if (is_array($value)) {
          if (!array_key_exists($key, $array2)) {
              $difference[$key] = $value;
           } else if (!is_array($array2[$key])) {
                $difference[$key] = $value;
           } else {
              $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
              if ($new_diff != FALSE) {
                  $difference[$key] = $new_diff;
               }
            }
         } elseif (!array_key_exists($key, $array2) || $array2[$key] != $value) {
               $difference[$key] = $value;
         }
       }
        return !isset($difference) ? 0 : $difference;
      }

     $result = array_diff_assoc_recursive($array1, $array2);
     echo '<pre>';
     print_r($result);