1 | <?php |
||
12 | abstract class Arr { |
||
13 | |||
14 | /** |
||
15 | * Get an array value by a given path, where path is an array of keys. |
||
16 | * This method is useful for accessing multidimensional arrays |
||
17 | * |
||
18 | * @return mixed|null : the value or null if the path does not exist |
||
19 | */ |
||
20 | |||
21 | public static function get(array $array, array $path) { |
||
31 | |||
32 | /** |
||
33 | * Select a set of elements from an array according to given keys. |
||
34 | * A result array can be optionally filtered by a given callback |
||
35 | */ |
||
36 | |||
37 | public static function select(array $array, array $keys, callable $filter = null) : array { |
||
38 | |||
39 | $selected = array_intersect_key($array, array_flip($keys)); |
||
40 | |||
41 | if (null !== $filter) $selected = array_filter($array, $filter); |
||
42 | |||
43 | # ------------------------ |
||
44 | |||
45 | return $selected; |
||
46 | } |
||
47 | |||
48 | /** |
||
49 | * Transform an associative array to indexed. Every element of a result array will be an array of type: |
||
50 | * [$key_name => old_key, $value_name => old_value] |
||
51 | */ |
||
52 | |||
53 | public static function index(array $array, string $key_name, string $value_name) : array { |
||
54 | |||
55 | $indexed = []; |
||
56 | |||
57 | foreach ($array as $key => $value) $indexed[] = [$key_name => $key, $value_name => $value]; |
||
58 | |||
59 | # ------------------------ |
||
60 | |||
61 | return $indexed; |
||
62 | } |
||
63 | |||
64 | /** |
||
65 | * Sort an array by a subvalue |
||
66 | */ |
||
67 | |||
68 | public static function sortby(array $array, $sub_key, bool $descending = false) : array { |
||
69 | |||
70 | $select_key = function ($element) use ($sub_key) { return ($element[$sub_key] ?? false); }; |
||
71 | |||
72 | $sorted = []; $column = array_map($select_key, $array); |
||
73 | |||
74 | if (!$descending) asort($column); else arsort($column); |
||
75 | |||
76 | foreach (array_keys($column) as $key) $sorted[$key] = $array[$key]; |
||
77 | |||
78 | # ------------------------ |
||
79 | |||
80 | return $sorted; |
||
81 | } |
||
82 | |||
83 | /** |
||
84 | * Get a random value from an array |
||
85 | * |
||
86 | * @return mixed|null : the value or null if the array is empty |
||
87 | */ |
||
88 | |||
89 | public static function random(array $array) { |
||
90 | |||
91 | return ($array[array_rand($array)] ?? null); |
||
92 | } |
||
93 | |||
94 | /** |
||
95 | * Encode an array into a 40-character hash string |
||
96 | */ |
||
97 | |||
98 | public static function encode(array $array) : string { |
||
99 | |||
100 | return sha1(serialize($array)); |
||
101 | } |
||
102 | } |
||
103 | } |
||
104 |