-
Notifications
You must be signed in to change notification settings - Fork 33
/
pluck.php
38 lines (34 loc) · 962 Bytes
/
pluck.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
namespace collections;
/**
* Returns an array of values belonging to a given property of each item in a collection.
*
* @param array $collection array
* @param string $property property name
*
* @return array
*/
function pluck(array $collection, $property)
{
return \array_map(function ($value) use ($property) {
if (isset($value[$property])) {
return $value[$property];
}
foreach (\explode('.', $property) as $segment) {
if (\is_object($value)) {
if (isset($value->{$segment})) {
$value = $value->{$segment};
} else {
return null;
}
} else {
if (isset($value[$segment])) {
$value = $value[$segment];
} else {
return null;
}
}
}
return $value;
}, (array)$collection);
}