Have an array with this expression $products[] = $product[$category_id][$product_id]
:
$products = array(
33 => array(
31 => array(
'model' => 'Product 4',
'product_id' => 31,
'sku' => '',
'ean' => '1234',
'price' => '80.0000'
),
8733 => array(
'model' => 'qqq',
'product_id' => 8733,
'sku' => '',
'ean' => '1000',
'price' => '344.6281'
)
),
25 => array(
30 => array(
'model' => 'Product 3',
'product_id' => 30,
'sku' => '',
'ean' => '250',
'price' => '50.4132'
),
31 => array(
'model' => 'Product 4',
'product_id' => 31,
'sku' => '',
'ean' => '1234',
'price' => '80.0000'
)
)
);
I need remove duplicated product in php and result must be:
$products = array(
33 => array(
8733 => array(
'model' => 'qqq',
'product_id' => 8733,
'sku' => '',
'ean' => '1000',
'price' => '344.6281'
)
),
25 => array(
30 => array(
'model' => 'Product 3',
'product_id' => 30,
'sku' => '',
'ean' => '250',
'price' => '50.4132'
),
31 => array(
'model' => 'Product 4',
'product_id' => 31,
'sku' => '',
'ean' => '1234',
'price' => '80.0000'
),
)
);
I have tried this:
$cleared_products = array();
foreach ($products as $category_id => $category_products) {
foreach ($category_products as $product_id => $product) {
if (isset($cleared_products[$category_id][$product_id])) {
unset($products[$category_id][$product_id]);
} else {
$cleared_products[$category_id][$product_id] = $product;
}
}
}
But does not work…
2
Answers
The problem with your code is that you check if the product exists within it’s category. In your example the duplicate product is in two categories.
We can adjust it easily by keeping track of the ID you added.
Important note: You don’t have control out of which category the item will be filtered
So the expected result is not matched with this code. If you define the priority of categories and sort on this, you can delete it where wanted.
Solution
Output:
Online Execution: 3v4l
Explanation:
$uniqueProducts
to store the products without duplicates.$products
array.$uniqueProducts
by comparing itsproduct_id
and details.$uniqueProducts
.