note 125666 deleted from function.array-unique by crell
| From: | crell@php.net | Date: | Tue, 12 Apr 2022 00:48:14 +0000 |
| Subject: | note 125666 deleted from function.array-unique by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-218161@lists.php.net to get a copy of this message | ||
Note Submitter: Eduardo Corts Vzquez (ecortes)
----
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'],
];
?>