1

I have 2 arrays:

Array ( [0] => Array ( [intTrackId] => 41 [intAverageRating] => 10 [bolNewRelease] => 0 [dtDateAdded] => 2013-03-08 17:32:26 ) [1] => Array ( [intTrackId] => 1 [intAverageRating] => 7 [bolNewRelease] => 0 [dtDateAdded] => 2013-03-08 18:54:35 ))

Array ( [0] => Array ( [intTrackId] => 41 [intAverageRating] => 5.5000 [bolNewRelease] => 1 [dtDateAdded] => 2014-03-25T09:39:28Q ) [1] => Array ( [intTrackId] => 361 [intAverageRating] => 8.0000 [bolNewRelease] => 1 [dtDateAdded] => 2014-03-25T09:39:28Q )) 

I want to remove the items in the second which have a matching track ID in the first. So in this example, I would get:

Array ( [0] => Array ( [intTrackId] => 361 [intAverageRating] => 8.0000 [bolNewRelease] => 1 [dtDateAdded] => 2014-03-25T09:39:28Q )) 

Is this possible with array_filter or is this a little complex for that?

Fraser
  • 14,036
  • 22
  • 73
  • 118

3 Answers3

1

Yes it can be done with array_filter:

$array1 = array(...);
$array2 = array(...);

$newArray = array_filter($array2, function($item) use ($array1){
    foreach($array1 as $elem){
        if($item['intTrackId'] == $elem['intTrackId']){
            return false;
        }
    }
    return true;
});
MrCode
  • 63,975
  • 10
  • 90
  • 112
1

I would first create a loop and store all track IDs from the first array in a separate array.

Then I'd loop over the second array and delete those keys that exist in the track ID array.

$track_ids = array();

foreach($array1 as $index => $items) {
   $track_ids[$items['intTrackId']] = $index;
}

foreach($array2 as $items) {
  if (isset($track_ids[$items['intTrackId']])) {
     unset($array2[$track_ids[$items['intTrackId']]]);
  }
}
silkfire
  • 24,585
  • 15
  • 82
  • 105
1

Just use array_udiff() - it's intended to do this:

$one = Array (
   0 => Array ('intTrackId' => 41, 'intAverageRating' => 10, 'bolNewRelease' => 0, 'dtDateAdded' => '2013-03-08 17:32:26' ), 
   1 => Array ('intTrackId' => 1, 'intAverageRating' => 7, 'bolNewRelease' => 0, 'dtDateAdded' => '2013-03-08 18:54:35' )
);

$two = Array ( 
   0 => Array ('intTrackId' => 41, 'intAverageRating' => 5.5000, 'bolNewRelease' => 1, 'dtDateAdded' => '2014-03-25T09:39:28Q' ), 
   1 => Array ('intTrackId' => 361, 'intAverageRating' => 8.0000, 'bolNewRelease' => 1, 'dtDateAdded' => '2014-03-25T09:39:28Q' )
);


$result = array_udiff($two, $one, function($x, $y)
{
   return $x['intTrackId']-$y['intTrackId'];
});
Alma Do
  • 37,009
  • 9
  • 76
  • 105