2016-09-13 88 views
1

我有兩個數組。其中之一是多維陣列,例如PHP - array_diff一個多維數組和一個平面數組

$products = array(
     0 => array(
      'product_id' => 33, 
      'variation_id' => 0, 
      'product_price' => 500.00 
     ), 
     1 => array(
      'product_id' => 45, 
      'variation_id' => 0, 
      'product_price' => 600.00 
     ), 
2 => array(
      'product_id' => 48, 
      'variation_id' => 0, 
      'product_price' => 600.00 
     ), 
     3 => array(
      'product_id' => 49, 
      'variation_id' => 0, 
      'product_price' => 600.00 
     ) 
    ); 

,我有一個平坦的陣列

$missingItems= array(49,33); 

我想從$刪除項目的產品,他們的product_id是在陣列missingItems字符串。

$diff = array(); 
foreach ($missingItems as $missingItem) { 
    foreach ($products as $product) { 
     if($missingItem != $product['product_id']){ 
      $diff[] = $missingItem; 
     }  
    } 
} 
echo '<pre>'; 
print_r($diff); 
echo '</pre>'; 

當我這樣做時,所有的值都被重複多次。例如如果我在我的第一個數組中有4個項目,而我的第二個項目中有兩個。共有8個結果。我只想出現2個,即不存在於第二個數組中的那些。

當我有兩個平面陣列我使用array_diff,但我不知道如何使用它在這種情況下,我有一個多維數組和平面數組。

+0

在你的輸出陣列,它應該返回與主鍵1和2的多維陣列?並刪除0和3? –

回答

4

使用array_filter()

$filtered = array_filter($products, function($product) use ($missingItems){ 
    return !in_array($product['product_id'], $missingItems); 
}); 
+2

這是最緊湊和最新穎的方法。做得太好了! :) –

1

可以使用in_array()檢查,並作出新的陣列

$diff = array(); 
foreach ($products as $product) { 
    if(!in_array($product['product_id'], $missingItems)){ 
    $diff[] = $product; 
    } 
} 
echo '<pre>'; 
print_r($diff); 
echo '</pre>'; 

我希望這將有助於實現你的目標

0

使用in_array ()

$diff = array(); 
foreach ($products as $product) { 
    if(!in_array($product['product_id'], $missingItems)){ 
    $diff[] = $product; 
    } 
} 
0

沒有必要不必要地遍歷您的$missingItems陣列。

in_array()有竅門。

foreach ($products as $k => $product) { 
    if (in_array($product['product_id'], $missingItems)) { 
     unset($products[$k]); 
    }  
}