forked from maciejczyzewski/bottomline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpluck.php
59 lines (54 loc) · 1.39 KB
/
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
namespace collections;
/**
* Returns an array of values belonging to a given property of each item in a collection.
*
* **Usage**
*
* ```php
* $a = [
* ['foo' => 'bar', 'bis' => 'ter' ],
* ['foo' => 'bar2', 'bis' => 'ter2'],
* ];
*
* __::pluck($a, 'foo');
* ```
*
* **Result**
*
* ```
* ['bar', 'bar2']
* ```
*
* @param array|object $collection Array or object that can be converted to array
* @param string $property property name
*
* @return array
*/
function pluck($collection, $property)
{
$result = \array_map(function ($value) use ($property) {
if (is_array($value) && isset($value[$property])) {
return $value[$property];
} elseif (\is_object($value) && isset($value->{$property})) {
return $value->{$property};
}
foreach (\__::split($property, \__::DOT_NOTATION_DELIMITER) 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);
return \array_values($result);
}