Skip to content
Advertisement

PHP array sort and remove duplicates by two field values

I have an array structure like this

  [0]=>array(3) {
    ["Number"]=> "L1"
    ["Location"]=> "Location-A"
    ["Qty"]=>"1"
  }
  [1]=>array(3) {
    ["Number"]=> "L1"
    ["Location"]=> "Location-B"
    ["Qty"]=> "5"
  }
  [2]=> array(3) {
    ["Number"]=> "L1"
    ["Location"]=> "Location-B"
    ["Qty"]=> "4"
  }
  [3]=>array(3) {
    ["Number"]=> "L2"
    ["Location"]=>  "Location-B"
    ["Qty"]=>  "5"
  }

But i required below structure as ouput

 [0]=>array(3) {
    ["Number"]=> "L1"
    ["Location"]=> "Location-A"
    ["Qty"]=>"1"
  }
  [1]=> array(3) {
    ["Number"]=> "L1"
    ["Location"]=> "Location-B"
    ["Qty"]=> "4"
  }
  [2]=>array(3) {
    ["Number"]=> "L2"
    ["Location"]=>  "Location-B"
    ["Qty"]=>  "5"
  }

How can i remove duplicate value by Number and Location?

ksort only works for one value, i need to remove by two values , how can i achieve this PHP ?

$ordered = array();
foreach ($data as $da) 
{           
    $ordered[$da['Number']] = $da;
    $ordered[$da['Location']] = $da;            
}
ksort($ordered);

Advertisement

Answer

Concatenate the two fields when creating your new array:

foreach ($data as $da) {
    $result[$da['Number'] . '.' . $da['Location']] = $da;
}
$result = array_values($result); // Turn it back into indexed array
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement