I need a advice from you. I have an array and I need to find arrays with same value of key. Then I need to compare another key of founded arrays and remove array which has lower value of key.
Example below.
As you can see, there are two arrays with same EAN key. I need to find arrays with same EAN. Then compare these two array by key ProductCount. The array with a higer ProdouctCount should be removed. Do you understand?
[20] => Array
(
[ean] => **6900532615069**
[productPrice] => 1140
[productCount] => 50
)
[25] => Array
(
[ean] => 6900535364122
[productPrice] => 1140
[productCount] => 50
)
[36] => Array
(
[ean] => **6900532615069**
[productPrice] => 1140
[productCount] => 10
)
function removeduplicateKeys($data){
$_data = array();
foreach ($data as $v) {
if (isset($_data[$v['ean']])) {
// found duplicate
continue;
}
// remember unique item
$_data[$v['ean']] = $v;
}
$data = array_values($_data);
return $data;
}
So output should be
[25] => Array
(
[ean] => 6900535364122
[productPrice] => 1140
[productCount] => 50
)
[36] => Array
(
[ean] => **6900532615069**
[productPrice] => 1140
[productCount] => 10
)
I am trying to do it for about three days but I do not how. The farthest thing I did was deleting a duplicate array but I don't know how to compare a key value and then delete the array. I would be grateful for any advice. Thank you.
You can use array_column to make the array associative.
This means it will overwrite any duplicate arrays also.
Then just array_values to set it back to original indexed keys.
$arr = array_values(array_column($arr, NULL, "ean"));
Edit: I see that you want keys 25 and 36.
The code above will give you 20 and 25.
To get your expected result you need to rsort the array first to make it backwards.
rsort($arr);
$arr = array_values(array_column($arr, NULL, "ean"));
The array_column will create an array like this:
[**6900532615069**] => Array
(
[ean] => **6900532615069**
[productPrice] => 1140
[productCount] => 50
)
[6900535364122] => Array
(
[ean] => 6900535364122
[productPrice] => 1140
[productCount] => 50
)
[**6900532615069**] => Array
(
[ean] => **6900532615069**
[productPrice] => 1140
[productCount] => 10
)
But since there can only be one array with the same key the second array will overwrite the first giving:
[6900535364122] => Array
(
[ean] => 6900535364122
[productPrice] => 1140
[productCount] => 50
)
[**6900532615069**] => Array
(
[ean] => **6900532615069**
[productPrice] => 1140
[productCount] => 10
)
If you use the rsort()
first it will remove the other array instead.
Array_values will then remove the "ean" from the array make it 0,1,2...
working code https://3v4l.org/sfPQr
if the array is unsorted you need to sort the array first on productcount.
usort($arr, function ($a, $b) {
return $b['productCount'] - $a['productCount'];
});
$arr = array_values(array_column($arr, NULL, "ean"));
var_dump($arr);