patternphpMinor
What is a better way to get unique array Items based on key in PHP?
Viewed 0 times
uniquewhatarrayphpwaybettergetitemsbasedkey
Problem
I'm trying to achieve a set of unique array with my following function.
The Function:
Example Array:
I then call the function like so:
But...
I wonder is there a better way to do the same ?
The Function:
/**
* uniqueAssocArray Removes arrys which have same keys
* @param Array $array Array to get unique items from
* @param String $uniqueKey the unique key
* @return Array new array with unique items
* @author Junaid Qadir Baloch
*/
function uniqueAssocArray($array, $uniqueKey) {
if (!is_array($array)) {
return array();
}
$uniqueKeys = array();
foreach ($array as $key => $item) {
if (!in_array($item[$uniqueKey], $uniqueKeys)) {
$uniqueKeys[$item[$uniqueKey]] = $item;
}
}
return $uniqueKeys;
}Example Array:
$actualArray = array(
user1 => array(
'name' => 'User1',
'age' => '25',
'lastLogin' => '2013-08-16'
),
user1 => array(
'name' => 'User1',
'age' => '25',
'lastLogin' => '2013-08-10'
),
user2 => array(
'name' => 'User2',
'age' => '35',
'lastLogin' => '2013-08-08'
),
user1 => array(
'name' => 'User1',
'age' => '25',
'lastLogin' => '2013-07-10'
)
);I then call the function like so:
$resultArray = uniqueAssocArray($actualArray, 'name');But...
I wonder is there a better way to do the same ?
Solution
Assuming your array is already sorted, you can just overwrite the values every time. Skip the inner if.
function uniqueAssocArray($array, $uniqueKey) {
if (!is_array($array)) {
return array();
}
$uniqueKeys = array();
foreach ($array as $key => $item) {
$groupBy=$item[$uniqueKey];
if (isset( $uniqueKeys[$groupBy]))
{
//compare $item with $uniqueKeys[$groupBy] and decide if you
//want to use the new item
$replace= ...
}
else
{
$replace=true;
}
if ($replace) $uniqueKeys[$groupBy] = $item;
}
return $uniqueKeys;
}Code Snippets
function uniqueAssocArray($array, $uniqueKey) {
if (!is_array($array)) {
return array();
}
$uniqueKeys = array();
foreach ($array as $key => $item) {
$groupBy=$item[$uniqueKey];
if (isset( $uniqueKeys[$groupBy]))
{
//compare $item with $uniqueKeys[$groupBy] and decide if you
//want to use the new item
$replace= ...
}
else
{
$replace=true;
}
if ($replace) $uniqueKeys[$groupBy] = $item;
}
return $uniqueKeys;
}Context
StackExchange Code Review Q#29835, answer score: 2
Revisions (0)
No revisions yet.