Skip to content

Commit 96d8e4a

Browse files
author
Roman Dubrovin
committed
Merge branch 'dpankratov/multidimension-array-unique' into 'master'
added ability to check unique multidimension arrays by array of keys and closure See merge request components/laravel-helpers!42
2 parents 0a9eea2 + 9b6443d commit 96d8e4a

File tree

1 file changed

+36
-4
lines changed

1 file changed

+36
-4
lines changed

src/helpers.php

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -271,21 +271,53 @@ function array_duplicate($array) {
271271
return array_diff_key($array, array_unique($array));
272272
}
273273

274-
function array_unique_object($objectsList, $key = 'id') {
274+
/**
275+
* Get only unique objects from array by key (array of keys) or by closure
276+
*
277+
* @param array $objectsList
278+
* @param string|callable|array $filter
279+
*
280+
* @return array
281+
*/
282+
function array_unique_objects($objectsList, $filter = 'id') {
275283
$uniqueKeys = [];
276284

277-
$uniqueObjects = array_map(function ($object) use (&$uniqueKeys, $key) {
278-
if (in_array($object[$key], $uniqueKeys)) {
285+
$uniqueObjects = array_map(function ($object) use (&$uniqueKeys, $filter) {
286+
if (is_string($filter)) {
287+
$value = $object[$filter];
288+
}
289+
290+
if (is_callable($filter)) {
291+
$value = $filter($object);
292+
}
293+
294+
if (is_array($filter)) {
295+
$value = array_only($object, $filter);
296+
}
297+
298+
if (in_array($value, $uniqueKeys)) {
279299
return null;
280300
}
281-
$uniqueKeys[] = $object[$key];
301+
$uniqueKeys[] = $value;
282302

283303
return $object;
284304
}, $objectsList);
285305

286306
return array_filter($uniqueObjects);
287307
}
288308

309+
/**
310+
* @deprecated
311+
*
312+
* @param array $objectsList
313+
* @param string|callable|array $filter
314+
*
315+
* @return array
316+
*/
317+
function array_unique_object($objectsList, $filter = 'id') {
318+
return array_unique_objects($objectsList, $filter);
319+
}
320+
289321
function array_trim($array)
290322
{
291323
return array_map(

0 commit comments

Comments
 (0)