0

I'm using PHP and have a pair of arrays of associative arrays, along the lines of:

{foo: [{id: 1, title: "one"}, {id: 2, title: "two"}]}
{bar: [{id: 2, title: "DEUX"}, {id: 3, title: "TROIS"}]}

I want to exclude any item from the first array where its ID appears in the second, so what in a sane language might be expressed as:

foo = foo.Where(x => !bar.Any(y => x.ID == y.ID));

The PHP manual appears to point to array_udiff as the tool for this job, so that I might use:

array_udiff($foo, $bar, function($x, $y) { ... });

with some suitable function that compares $x['id'] with $y['id'].

I was expecting the function to be called with each possible pair of $x and $y, i.e. such that a function($x, $y) { print $x['title'] . ", " . $y['title']; return 0;} would output something like:

  • one, DEUX
  • one, TROIS
  • two, DEUX
  • two, TROIS

with $x always a value from the first array and $y one from the second.

What's actually being passed in is a complete mish-mash of values from each array which makes no sense to me at all, e.g.

  • two, one
  • TROIS, DEUX
  • two, TROIS
  • two, one

Can anyone please explain what's going on?

Complete code producing the above output:

$foo[] = array('id' => 1, 'title' => 'one');
$foo[] = array('id' => 2, 'title' => 'two');
$bar[] = array('id' => 2, 'title' => 'DEUX');
$bar[] = array('id' => 3, 'title' => 'TROIS');
array_udiff($foo, $bar, function($x, $y) { print $x['title'] . ", " . $y['title'] . "\n"; return 0;});

Thanks.

stovroz
  • 6,315
  • 2
  • 42
  • 57

0 Answers0