0

I am trying to accomplish this without nested loops. I have the following 2 arrays:

$arr1 = array(
   0 => array(
      "key" => 1,
      "value" => "Test 1"
   ),
   1 => array(
      "key" => 35
      "value" => "Test 2"
   )
   ...
);

$arr2 = array(
   0 => array(
      "key" => 1,
      "value" => "Test 1"
   )
   ...
);

print_r(array_diff_magic($arr1, $arr2));

Returns all items in array 1 that was removed from array 2 but by comparing the "key" values of sub arrays. Can not use array_diff_keys because need to compare sub array's "keys" instead of the keys of the main array. The output should be something like this:

array(1) {
  [0] => array(2) {
     ["key"] => 35,
     ["value"] => "Test 2"
  }
}

Is there a way to do this without using nested foreach loops?

GGio
  • 7,563
  • 11
  • 44
  • 81
  • http://stackoverflow.com/questions/3876435/recursive-array-diff – adeneo Apr 24 '15 at 16:14
  • @adeneo but that compares keys as opposed to my custom "key". – GGio Apr 24 '15 at 16:16
  • while `array_udiff` will work and isn't using nested loops, you can bet internally it would be same as a nested loop (but native). You can possible work faster with nested loops if you could guarantee some stuff like `key` doesn't exist more than once in each array (if you loop over the first array then loop over the second array you can break out of the inner loop soon as you find matching `key` in the second array) or are the sub-arrays sorted in order of `key`. Perhaps even the structure should be different with `key=>value` which would be easier to diff with direct index lookups. – Jonathan Kuhn Apr 24 '15 at 22:56

1 Answers1

1

Try array_udiff to get difference, followed by array_values to start index of resulting array at 0:

$arr3 = array_values(array_udiff($arr1, $arr2, function($a, $b) {
    return $a['key'] - $b['key'];
}));
mhall
  • 3,671
  • 3
  • 23
  • 35