I'm trying to achieve a set of unique array with my following function.
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 <[email protected]>
*/
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 ?