note 118132 deleted from function.array-unique by crell
| From: | crell@php.net | Date: | Tue, 12 Apr 2022 00:47:18 +0000 |
| Subject: | note 118132 deleted from function.array-unique by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-218156@lists.php.net to get a copy of this message | ||
Note Submitter: tim at heuer dot nz
----
I created a function for doing array_unique with a custom in_array function. So, if elements are
considered in the array passed to this function, the array returned won't include elements that
are considered equal and only return the values from the first array that are not considered in the
array:
<?php
function uniqueBy(array $array, callable $in_array_func) {
$result = array();
foreach ($array as $key => $item) {
if (!$in_array_func($item, $result)) {
$result[$key] = $item;
}
}
return $result;
}
?>
Example usage:
<?php
$in_array_func = function($item, $array) {
$fromBower = function($item) {
$result = substr($item, strpos($item, 'bower_components'));
return $result;
};
foreach ($array as $myItem) {
if ($fromBower($item) == $fromBower($myItem)) {
return true;
}
}
return false;
};
// ...
$jss = uniqueBy($jss, $in_array_func);
?>