Reputation: 117
I have an array like this:
Array
(
[0] => Array
(
[CommodityID] => 10
[RetailerID] => 1798
[Name] => Petrol
[City] => Parow
[Line1] => 49 Fifth Avenue
[Line2] =>
[Line3] =>
[ContractorName] => BP Fifth Ave Motors Parow
[AreaCode] => 021
[Number] => 9305025
[Latitude] => -33.896493
[Longitude] => 18.579302
[LogoUrl] => https://webservices.test.com/ContractorLogos/bp.png
[dist] => 0.00
)
[1] => Array
(
[CommodityID] => 10
[RetailerID] => 1798
[Name] => Petrol
[City] => Parow
[Line1] => 49 Fifth Avenue
[Line2] =>
[Line3] =>
[ContractorName] => BP Fifth Ave Motors Parow
[AreaCode] => 021
[Number] => 9305025
[Latitude] => -33.896493
[Longitude] => 18.579302
[LogoUrl] => https://webservices.test.com/ContractorLogos/bp.png
[dist] => 0.00
)
[2] => Array
(
[CommodityID] => 22
[RetailerID] => 1758
[Name] => Jewellers
[City] => Parow
[Line1] => Shop 4
[Line2] => Mc Intyre Square
[Line3] => Mc Intyre Road
[ContractorName] => Du Plessis Manufacturing Jewellers Parow
[AreaCode] => 021
[Number] => 9300788
[Latitude] => -33.895200
[Longitude] => 18.586710
[LogoUrl] => https://webservices.test.com/ContractorLogos/DuPlessisJewellers.png
[dist] => 0.01
)
)
I simply want to have only unique [RetailerID] i.e:
Array
(
[0] => Array
(
[CommodityID] => 10
[RetailerID] => 1798
[Name] => Petrol
[City] => Parow
[Line1] => 49 Fifth Avenue
[Line2] =>
[Line3] =>
[ContractorName] => BP Fifth Ave Motors Parow
[AreaCode] => 021
[Number] => 9305025
[Latitude] => -33.896493
[Longitude] => 18.579302
[LogoUrl] => https://webservices.test.com/ContractorLogos/bp.png
[dist] => 0.00
)
[1] => Array
(
[CommodityID] => 22
[RetailerID] => 1758
[Name] => Jewellers
[City] => Parow
[Line1] => Shop 4
[Line2] => Mc Intyre Square
[Line3] => Mc Intyre Road
[ContractorName] => Du Plessis Manufacturing Jewellers Parow
[AreaCode] => 021
[Number] => 9300788
[Latitude] => -33.895200
[Longitude] => 18.586710
[LogoUrl] => https://webservices.test.com/ContractorLogos/DuPlessisJewellers.png
[dist] => 0.01
)
)
I have tried array_unique, but that seems to make it unique based on all columns. Is there a php built-in function that can do this by looking at just one array key's value?
Upvotes: 1
Views: 514
Reputation: 1416
would iterate the array once and save only unique values by that field once, for example:
$newArray = array();
foreach($array as $item) {
$newArray[$item['RetailerID']] = $item;
}
this will always save only the last item of the same kind. you can modify the logic to match your needs. another, more safe possibility would be saving the unique values and checking them:
$exists = array();
$newArray = array();
foreach($array as $item) {
if(!in_array($item['RetailerID'],$exists)){
$newArray[$item['RetailerID']] = $item;
$exists[] = $item['RetailerID'];
}
}
Upvotes: 1