2

I have two arrays. One of them is a multidimensional array e.g.

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

and I have a flat array

$missingItems= array(49,33);

I would like to remove items from $products where their product_id is in the array missingItems string.

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

When I do this, all the values are being repeated multiple times. e.g. if I have 4 items in my first array, and two in my second. There are 8 results. I would like only 2 to appear i.e. those that are not present in the second array.

When I have two flat arrays I use array_diff but I'm not sure how to use it in this case where I have a multidimensional array and a flat array.

1
  • In your output array, should it return a multi dimensional array with main keys 1 and 2? And remove 0 and 3? Commented Sep 13, 2016 at 11:35

4 Answers 4

7

Use array_filter():

$filtered = array_filter($products, function($product) use ($missingItems){
    return !in_array($product['product_id'], $missingItems);
});
Sign up to request clarification or add additional context in comments.

Comments

1

you can use in_array() to check and make new array

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

I hope this will help to achieve your goal

Comments

0

Use in_array()

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

Comments

0

There's no need to unnecessarily traverse through your $missingItems array.

in_array() does the trick.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.