note 113775 added to function.array-unique
| From: | CertaiN | Date: | Fri, 29 Nov 2013 14:58:22 +0000 |
| Subject: | note 113775 added to function.array-unique | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-197662@lists.php.net to get a copy of this message | ||
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
)
)
----
Server IP: 64.71.164.2
Probable Submitter: 219.209.194.119
----
Manual Page -- http://php.net/manual/en/function.array-unique.php
Edit -- https://master.php.net/note/edit/113775
Del: integrated -- https://master.php.net/note/delete/113775/integrated
Del: useless -- https://master.php.net/note/delete/113775/useless
Del: bad code -- https://master.php.net/note/delete/113775/bad+code
Del: spam -- https://master.php.net/note/delete/113775/spam
Del: non-english -- https://master.php.net/note/delete/113775/non-english
Del: in docs -- https://master.php.net/note/delete/113775/in+docs
Del: other reasons-- https://master.php.net/note/delete/113775
Reject -- https://master.php.net/note/reject/113775
Search -- https://master.php.net/manage/user-notes.php