Last active
January 10, 2021 20:49
-
-
Save Doomd/6af37ba6796cc9e6cd08b21ddf4a27c4 to your computer and use it in GitHub Desktop.
PHP - Create Unique Array of Object by comparing one property
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
{ | |
"offer_nid": "16524", | |
"offer_lm": "1610224798", | |
"biz_nid": "73865", | |
"biz_lm": "1602519728", | |
"geo": "9xjhn", | |
"counter": "1" | |
}, | |
{ | |
"offer_nid": "16524", | |
"offer_lm": "1610224798", | |
"biz_nid": "81583", | |
"biz_lm": "1605971711", | |
"geo": "9xjhn", | |
"counter": "2" | |
}, | |
{ | |
"offer_nid": "82114", | |
"offer_lm": "1610128855", | |
"biz_nid": "73217", | |
"biz_lm": "1601659864", | |
"geo": "9xjhn", | |
"counter": "3" | |
}, | |
{ | |
"offer_nid": "82113", | |
"offer_lm": "1610128855", | |
"biz_nid": "73209", | |
"biz_lm": "1601659864", | |
"geo": "9xjqb", | |
"counter": "4" | |
}, | |
] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Let's imagine you have a JSON array: | |
$geohases = "./geohashes.json" | |
$jsonRequest = getJSON($geohases); | |
$jsonArray = json_decode($latestIndex); | |
// But you want to filter out objects you consider "duplicates" because of a duplicate property. | |
// First, make a unique array chosing one of the object properties: | |
function returnUniqueObjects($array, $property) { | |
// Technically, this will consider objects unique by comparing only ONE of the objects' properties | |
$tempArray = array_unique(array_column($array, $property)); | |
// With our temporary unique one-dimensional array, we have the indexes of unique objects. Let's use that index to retrieve matches: | |
$onePropertyUniqueArrayOfObjects = array_values(array_intersect_key($array, $tempArray)); | |
return $onePropertyUniqueArrayOfObjects; | |
} | |
$unique = returnUniqueObjects($jsonArray, "geo"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment