note 113775 deleted from function.array-unique by cmb
| From: | cmb@php.net | Date: | Sun, 27 Oct 2019 08:43:18 +0000 |
| Subject: | note 113775 deleted from function.array-unique by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212802@lists.php.net to get a copy of this message | ||
Note Submitter: CertaiN
----
Let's implement array_unique_callback() !
Function:
<?php
function array_unique_callback(array $arr, callable $callback, $strict = false) {
return array_filter(
$arr,
function ($item) use ($strict, $callback) {
static $haystack = array();
$needle = $callback($item);
if (in_array($needle, $haystack, $strict)) {
return false;
} else {
$haystack[] = $needle;
return true;
}
}
);
}
?>
Usage:
<?php
$companies = array(
0 => array(
'name' => 'Foo - Ltd.',
'phone' => 'XXX-YYY-ZZZ',
'category' => 'supplyment',
),
1 => array(
'name' => 'Bar - Ltd.',
'phone' => 'xxx-yyy-zzz',
'category' => 'supplyment',
),
2 => array(
'name' => 'Baz - Ltd.',
'phone' => 'AAA-BBB-CCC',
'category' => 'alcohol',
),
);
$companies = array_unique_callback(
$companies,
function ($company) {
return $company['category'];
}
);
print_r($companies);
?>
Result:
Array
(
[0] => Array
(
[name] => Foo - Ltd.
[phone] => XXX-YYY-ZZZ
[category] => supplyment
)
[2] => Array
(
[name] => Baz - Ltd.
[phone] => AAA-BBB-CCC
[category] => alcohol
)
)