根据另一个数组中的项目从数组中删除项目

时间:2014-03-25 09:43:12

标签: php arrays

我有2个阵列:

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 )) 

我想删除第二个中具有匹配轨道ID的项目。所以在这个例子中,我会得到:

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

对于array_filter这是否可行,或者这有点复杂?

3 个答案:

答案 0 :(得分:1)

是的,可以使用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;
});

答案 1 :(得分:1)

我首先创建一个循环并将第一个数组中的所有轨道ID存储在一个单独的数组中。

然后我循环遍历第二个数组并删除轨道ID数组中存在的那些键。

$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']]]);
  }
}

答案 2 :(得分:1)

只需使用array_udiff() - 它的目的就是:

$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'];
});