Click here to Skip to main content
15,887,175 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, I would like to find arrays with same value of key EAN. If multiple records exist, I want to remove the record with lower value of key ProductCount.

For example I have an array. As you can see there are three records with thesame ean ($arr[0], $arr[1], $a[3]). After finding these records with the same ean I need to compare their values of key ProductCount and keep the record with the smallest value of ProductCount. Do you understand?

I would be thankful for any advice.

PHP
$arr =array( 
"0" => Array
    (
        "ean" => 6900532615069,
        "productPrice" => 1140,
        "productCount" => 5
    ),
"1" => Array
    (
        "ean" => 6900532615069,
        "productPrice" => 1140,
        "productCount" => 50
    ),
"2" => Array
    (
        "ean" => 6900535364122,
        "productPrice" => 1140,
        "productCount" => 50
    ),

"3" => Array
    (
        "ean" => 6900532615069,
        "productPrice" => 1140,
        "productCount" => 10,
    ));


So output should be

PHP
$arr =array( 
"0" => Array
    (
        "ean" => 6900532615069,
        "productPrice" => 1140,
        "productCount" => 5
    ),
"1" => Array
    (
        "ean" => 6900535364122,
        "productPrice" => 1140,
        "productCount" => 50
    ));


What I have tried:

I tried this and some modifications of this but without success. I am trying to do it for days :(

PHP
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;

}
Posted
Updated 5-Sep-18 3:16am

1 solution

The very most basic way is to loop through your array - which has numeric indices.

Each time compare product count of the old ean to the new ean value. Keep the lower value and its index. When you've finished the loop you have the index. (Figure out what to do if a tie is possible and occurs).

The above is can be applied very generally to find min's and max's.

 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900