note 125666 added to function.array-unique
| From: | (ecortes) | Date: | Fri, 08 Jan 2021 22:19:42 +0000 |
| Subject: | note 125666 added to function.array-unique | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-216075@lists.php.net to get a copy of this message | ||
Create multidimensional array unique for any single key index.
<?php
$users = [
['id' => 1, 'name' => 'ecortes', 'phone' =>
'1111111'],
['id' => 2, 'name' => 'canepa', 'phone' =>
'222222'],
['id' => 1, 'name' => 'john', 'phone' =>
'3333333'],
];
function array_unique_multi($array, $key) {
return array_reduce($array, function($acc, $curr) use($key) {
if(!in_array($curr[$key], array_column($acc, $key))) {
array_push($acc, $curr);
}
return $acc;
}, []);
}
//Call the function
$unique_users = array_unique_multi($users, 'id');
//output
$users = [
['id' => 1, 'name' => 'ecortes', 'phone' =>
'1111111'],
['id' => 2, 'name' => 'canepa', 'phone' =>
'222222'],
];
?>
----
Server IP: 45.112.84.4
Probable Submitter: 45.91.159.165 (proxied: 201.144.227.194)
----
Manual Page -- http://php.net/manual/en/function.array-unique.php
Edit -- https://master.php.net/note/edit/125666
Del: integrated -- https://master.php.net/note/delete/125666/integrated
Del: useless -- https://master.php.net/note/delete/125666/useless
Del: bad code -- https://master.php.net/note/delete/125666/bad+code
Del: spam -- https://master.php.net/note/delete/125666/spam
Del: non-english -- https://master.php.net/note/delete/125666/non-english
Del: in docs -- https://master.php.net/note/delete/125666/in+docs
Del: other reasons-- https://master.php.net/note/delete/125666
Reject -- https://master.php.net/note/reject/125666
Search -- https://master.php.net/manage/user-notes.php