Reputation: 119
Please Help! I want to validate array with duplicate sub-array values. I have an multi-dimensional array. I want to return keys of sub-array with duplicate product_id value. Example: In my array, I have sub-array with duplicate product_id = 124. I want to return their key.
[purchase_order_products] => Array
(
[0] => Array
(
[product_id] => 124
[barcode] => 480001407081
[item_code] =>
[name] => Brew Kettle Can 330mL
[qty] =>
[unit] => 2
[pcs_have] => 1
[total_pcs] => 1
[cost] => 34.83
[total_item_price] => 34.83
[stocks] =>
[po_qty] =>
)
[1] => Array
(
[product_id] => 125
[barcode] => 480001416108
[item_code] =>
[name] => Colt 45 Can 330mL
[qty] =>
[unit] => 2
[pcs_have] => 1
[total_pcs] => 1
[cost] => 29.58
[total_item_price] => 29.58
[stocks] =>
[po_qty] =>
)
[2] => Array
(
[product_id] => 124
[barcode] => 480001407081
[item_code] =>
[name] => Brew Kettle Can 330mL
[qty] =>
[unit] => 2
[pcs_have] => 1
[total_pcs] => 1
[cost] => 34.83
[total_item_price] => 34.83
[stocks] =>
[po_qty] =>
)
)
The output I want is:
Array(0,2)
Upvotes: 3
Views: 225
Reputation: 710
Edit: I've updated the answer quite a bit.
Edit 2: Now utilizing the built in array functions to find the duplicates
$products = [
0 => ['product-id' => 124],
1 => ['product-id' => 125],
2 => ['product-id' => 124],
3 => ['product-id' => 126],
4 => ['product-id' => 126],
8 => ['product-id' => 124],
];
// Find the duplicates
$product_ids = array_column($products, 'product-id');
$count = array_count_values($product_ids);
$duplicates = array_filter($count, function($var) {
return $var > 1;
});
// List all the entries with duplicate ids:
foreach ( array_flip($duplicates) as $product_id ) {
$filter = array_filter($products, function($var) use ($product_id) {
return ( $var['product-id'] === $product_id );
});
print_r('Product-id: ' . $product_id . ' is duplicated in entries: ');
print_r(array_keys($filter));
}
The output:
// Product-id: 124 is duplicated in entries: Array
// (
// [0] => 0
// [1] => 2
// [2] => 8
// )
// Product-id: 126 is duplicated in entries: Array
// (
// [0] => 3
// [1] => 4
// )
Upvotes: 1
Reputation: 721
Use this code to get key for duplicate product id:
$products = $array['purchase_order_products'];
$duplicate_products_keys = array();
$products_ids = array();
foreach($products as $key => $product) {
if(in_array($product['product_id'], $products_ids)) {
$duplicate_products_keys[] = $key;
}
$products_ids[$product['product_id']] = $product['product_id'];
}
prinr_r($duplicate_products_keys);
Upvotes: 1