1 | <?php |
||
2 | /** |
||
3 | * @link http://www.yiiframework.com/ |
||
4 | * @copyright Copyright (c) 2008 Yii Software LLC |
||
5 | * @license http://www.yiiframework.com/license/ |
||
6 | */ |
||
7 | |||
8 | namespace yii\helpers; |
||
9 | |||
10 | use ArrayAccess; |
||
11 | use Traversable; |
||
12 | use Yii; |
||
13 | use yii\base\Arrayable; |
||
14 | use yii\base\InvalidArgumentException; |
||
15 | |||
16 | /** |
||
17 | * BaseArrayHelper provides concrete implementation for [[ArrayHelper]]. |
||
18 | * |
||
19 | * Do not use BaseArrayHelper. Use [[ArrayHelper]] instead. |
||
20 | * |
||
21 | * @author Qiang Xue <[email protected]> |
||
22 | * @since 2.0 |
||
23 | */ |
||
24 | class BaseArrayHelper |
||
25 | { |
||
26 | /** |
||
27 | * Converts an object or an array of objects into an array. |
||
28 | * @param object|array|string $object the object to be converted into an array |
||
29 | * @param array $properties a mapping from object class names to the properties that need to put into the resulting arrays. |
||
30 | * The properties specified for each class is an array of the following format: |
||
31 | * |
||
32 | * ```php |
||
33 | * [ |
||
34 | * 'app\models\Post' => [ |
||
35 | * 'id', |
||
36 | * 'title', |
||
37 | * // the key name in array result => property name |
||
38 | * 'createTime' => 'created_at', |
||
39 | * // the key name in array result => anonymous function |
||
40 | * 'length' => function ($post) { |
||
41 | * return strlen($post->content); |
||
42 | * }, |
||
43 | * ], |
||
44 | * ] |
||
45 | * ``` |
||
46 | * |
||
47 | * The result of `ArrayHelper::toArray($post, $properties)` could be like the following: |
||
48 | * |
||
49 | * ```php |
||
50 | * [ |
||
51 | * 'id' => 123, |
||
52 | * 'title' => 'test', |
||
53 | * 'createTime' => '2013-01-01 12:00AM', |
||
54 | * 'length' => 301, |
||
55 | * ] |
||
56 | * ``` |
||
57 | * |
||
58 | * @param bool $recursive whether to recursively converts properties which are objects into arrays. |
||
59 | * @return array the array representation of the object |
||
60 | */ |
||
61 | 26 | public static function toArray($object, $properties = [], $recursive = true) |
|
62 | { |
||
63 | 26 | if (is_array($object)) { |
|
64 | 26 | if ($recursive) { |
|
65 | 26 | foreach ($object as $key => $value) { |
|
66 | 26 | if (is_array($value) || is_object($value)) { |
|
67 | 26 | $object[$key] = static::toArray($value, $properties, true); |
|
68 | } |
||
69 | } |
||
70 | } |
||
71 | |||
72 | 26 | return $object; |
|
73 | 8 | } elseif (is_object($object)) { |
|
74 | 8 | if (!empty($properties)) { |
|
75 | 1 | $className = get_class($object); |
|
76 | 1 | if (!empty($properties[$className])) { |
|
77 | 1 | $result = []; |
|
78 | 1 | foreach ($properties[$className] as $key => $name) { |
|
79 | 1 | if (is_int($key)) { |
|
80 | 1 | $result[$name] = $object->$name; |
|
81 | } else { |
||
82 | 1 | $result[$key] = static::getValue($object, $name); |
|
83 | } |
||
84 | } |
||
85 | |||
86 | 1 | return $recursive ? static::toArray($result, $properties) : $result; |
|
87 | } |
||
88 | } |
||
89 | 8 | if ($object instanceof Arrayable) { |
|
90 | 1 | $result = $object->toArray([], [], $recursive); |
|
91 | } else { |
||
92 | 8 | $result = []; |
|
93 | 8 | foreach ($object as $key => $value) { |
|
94 | 8 | $result[$key] = $value; |
|
95 | } |
||
96 | } |
||
97 | |||
98 | 8 | return $recursive ? static::toArray($result, $properties) : $result; |
|
99 | } |
||
100 | |||
101 | 1 | return [$object]; |
|
102 | } |
||
103 | |||
104 | /** |
||
105 | * Merges two or more arrays into one recursively. |
||
106 | * If each array has an element with the same string key value, the latter |
||
107 | * will overwrite the former (different from array_merge_recursive). |
||
108 | * Recursive merging will be conducted if both arrays have an element of array |
||
109 | * type and are having the same key. |
||
110 | * For integer-keyed elements, the elements from the latter array will |
||
111 | * be appended to the former array. |
||
112 | * You can use [[UnsetArrayValue]] object to unset value from previous array or |
||
113 | * [[ReplaceArrayValue]] to force replace former value instead of recursive merging. |
||
114 | * @param array $a array to be merged to |
||
115 | * @param array $b array to be merged from. You can specify additional |
||
116 | * arrays via third argument, fourth argument etc. |
||
117 | * @return array the merged array (the original arrays are not changed.) |
||
118 | */ |
||
119 | 5350 | public static function merge($a, $b) |
|
120 | { |
||
121 | 5350 | $args = func_get_args(); |
|
122 | 5350 | $res = array_shift($args); |
|
123 | 5350 | while (!empty($args)) { |
|
124 | 5350 | foreach (array_shift($args) as $k => $v) { |
|
125 | 1122 | if ($v instanceof UnsetArrayValue) { |
|
126 | 1 | unset($res[$k]); |
|
127 | 1122 | } elseif ($v instanceof ReplaceArrayValue) { |
|
128 | 1 | $res[$k] = $v->value; |
|
129 | 1122 | } elseif (is_int($k)) { |
|
130 | 5 | if (array_key_exists($k, $res)) { |
|
131 | 5 | $res[] = $v; |
|
132 | } else { |
||
133 | 5 | $res[$k] = $v; |
|
134 | } |
||
135 | 1120 | } elseif (is_array($v) && isset($res[$k]) && is_array($res[$k])) { |
|
136 | 231 | $res[$k] = static::merge($res[$k], $v); |
|
137 | } else { |
||
138 | 1122 | $res[$k] = $v; |
|
139 | } |
||
140 | } |
||
141 | } |
||
142 | |||
143 | 5350 | return $res; |
|
144 | } |
||
145 | |||
146 | /** |
||
147 | * Retrieves the value of an array element or object property with the given key or property name. |
||
148 | * If the key does not exist in the array, the default value will be returned instead. |
||
149 | * Not used when getting value from an object. |
||
150 | * |
||
151 | * The key may be specified in a dot format to retrieve the value of a sub-array or the property |
||
152 | * of an embedded object. In particular, if the key is `x.y.z`, then the returned value would |
||
153 | * be `$array['x']['y']['z']` or `$array->x->y->z` (if `$array` is an object). If `$array['x']` |
||
154 | * or `$array->x` is neither an array nor an object, the default value will be returned. |
||
155 | * Note that if the array already has an element `x.y.z`, then its value will be returned |
||
156 | * instead of going through the sub-arrays. So it is better to be done specifying an array of key names |
||
157 | * like `['x', 'y', 'z']`. |
||
158 | * |
||
159 | * Below are some usage examples, |
||
160 | * |
||
161 | * ```php |
||
162 | * // working with array |
||
163 | * $username = \yii\helpers\ArrayHelper::getValue($_POST, 'username'); |
||
164 | * // working with object |
||
165 | * $username = \yii\helpers\ArrayHelper::getValue($user, 'username'); |
||
166 | * // working with anonymous function |
||
167 | * $fullName = \yii\helpers\ArrayHelper::getValue($user, function ($user, $defaultValue) { |
||
168 | * return $user->firstName . ' ' . $user->lastName; |
||
169 | * }); |
||
170 | * // using dot format to retrieve the property of embedded object |
||
171 | * $street = \yii\helpers\ArrayHelper::getValue($users, 'address.street'); |
||
172 | * // using an array of keys to retrieve the value |
||
173 | * $value = \yii\helpers\ArrayHelper::getValue($versions, ['1.0', 'date']); |
||
174 | * ``` |
||
175 | * |
||
176 | * @param array|object $array array or object to extract value from |
||
177 | * @param string|\Closure|array $key key name of the array element, an array of keys or property name of the object, |
||
178 | * or an anonymous function returning the value. The anonymous function signature should be: |
||
179 | * `function($array, $defaultValue)`. |
||
180 | * The possibility to pass an array of keys is available since version 2.0.4. |
||
181 | * @param mixed $default the default value to be returned if the specified array key does not exist. Not used when |
||
182 | * getting value from an object. |
||
183 | * @return mixed the value of the element if found, default value otherwise |
||
184 | */ |
||
185 | 694 | public static function getValue($array, $key, $default = null) |
|
186 | { |
||
187 | 694 | if ($key instanceof \Closure) { |
|
188 | 21 | return $key($array, $default); |
|
189 | } |
||
190 | |||
191 | 692 | if (is_array($key)) { |
|
192 | 2 | $lastKey = array_pop($key); |
|
193 | 2 | foreach ($key as $keyPart) { |
|
194 | 2 | $array = static::getValue($array, $keyPart); |
|
195 | } |
||
196 | 2 | $key = $lastKey; |
|
197 | } |
||
198 | |||
199 | 692 | if (is_object($array) && property_exists($array, $key)) { |
|
200 | 11 | return $array->$key; |
|
201 | } |
||
202 | |||
203 | 685 | if (static::keyExists($key, $array)) { |
|
204 | 644 | return $array[$key]; |
|
205 | } |
||
206 | |||
207 | 81 | if (($pos = strrpos($key, '.')) !== false) { |
|
208 | 48 | $array = static::getValue($array, substr($key, 0, $pos), $default); |
|
209 | 48 | $key = substr($key, $pos + 1); |
|
210 | } |
||
211 | |||
212 | 81 | if (static::keyExists($key, $array)) { |
|
213 | 18 | return $array[$key]; |
|
214 | } |
||
215 | 70 | if (is_object($array)) { |
|
216 | // this is expected to fail if the property does not exist, or __get() is not implemented |
||
217 | // it is not reliably possible to check whether a property is accessible beforehand |
||
218 | try { |
||
219 | 3 | return $array->$key; |
|
220 | 1 | } catch (\Exception $e) { |
|
221 | 1 | if ($array instanceof ArrayAccess) { |
|
222 | 1 | return $default; |
|
223 | } |
||
224 | throw $e; |
||
225 | } |
||
226 | } |
||
227 | |||
228 | 68 | return $default; |
|
229 | } |
||
230 | |||
231 | /** |
||
232 | * Writes a value into an associative array at the key path specified. |
||
233 | * If there is no such key path yet, it will be created recursively. |
||
234 | * If the key exists, it will be overwritten. |
||
235 | * |
||
236 | * ```php |
||
237 | * $array = [ |
||
238 | * 'key' => [ |
||
239 | * 'in' => [ |
||
240 | * 'val1', |
||
241 | * 'key' => 'val' |
||
242 | * ] |
||
243 | * ] |
||
244 | * ]; |
||
245 | * ``` |
||
246 | * |
||
247 | * The result of `ArrayHelper::setValue($array, 'key.in.0', ['arr' => 'val']);` will be the following: |
||
248 | * |
||
249 | * ```php |
||
250 | * [ |
||
251 | * 'key' => [ |
||
252 | * 'in' => [ |
||
253 | * ['arr' => 'val'], |
||
254 | * 'key' => 'val' |
||
255 | * ] |
||
256 | * ] |
||
257 | * ] |
||
258 | * |
||
259 | * ``` |
||
260 | * |
||
261 | * The result of |
||
262 | * `ArrayHelper::setValue($array, 'key.in', ['arr' => 'val']);` or |
||
263 | * `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);` |
||
264 | * will be the following: |
||
265 | * |
||
266 | * ```php |
||
267 | * [ |
||
268 | * 'key' => [ |
||
269 | * 'in' => [ |
||
270 | * 'arr' => 'val' |
||
271 | * ] |
||
272 | * ] |
||
273 | * ] |
||
274 | * ``` |
||
275 | * |
||
276 | * @param array $array the array to write the value to |
||
277 | * @param string|array|null $path the path of where do you want to write a value to `$array` |
||
278 | * the path can be described by a string when each key should be separated by a dot |
||
279 | * you can also describe the path as an array of keys |
||
280 | * if the path is null then `$array` will be assigned the `$value` |
||
281 | * @param mixed $value the value to be written |
||
282 | * @since 2.0.13 |
||
283 | */ |
||
284 | 16 | public static function setValue(&$array, $path, $value) |
|
285 | { |
||
286 | 16 | if ($path === null) { |
|
287 | 1 | $array = $value; |
|
288 | 1 | return; |
|
289 | } |
||
290 | |||
291 | 15 | $keys = is_array($path) ? $path : explode('.', $path); |
|
292 | |||
293 | 15 | while (count($keys) > 1) { |
|
294 | 12 | $key = array_shift($keys); |
|
295 | 12 | if (!isset($array[$key])) { |
|
296 | 4 | $array[$key] = []; |
|
297 | } |
||
298 | 12 | if (!is_array($array[$key])) { |
|
299 | 2 | $array[$key] = [$array[$key]]; |
|
300 | } |
||
301 | 12 | $array = &$array[$key]; |
|
302 | } |
||
303 | |||
304 | 15 | $array[array_shift($keys)] = $value; |
|
305 | 15 | } |
|
306 | |||
307 | /** |
||
308 | * Removes an item from an array and returns the value. If the key does not exist in the array, the default value |
||
309 | * will be returned instead. |
||
310 | * |
||
311 | * Usage examples, |
||
312 | * |
||
313 | * ```php |
||
314 | * // $array = ['type' => 'A', 'options' => [1, 2]]; |
||
315 | * // working with array |
||
316 | * $type = \yii\helpers\ArrayHelper::remove($array, 'type'); |
||
317 | * // $array content |
||
318 | * // $array = ['options' => [1, 2]]; |
||
319 | * ``` |
||
320 | * |
||
321 | * @param array $array the array to extract value from |
||
322 | * @param string $key key name of the array element |
||
323 | * @param mixed $default the default value to be returned if the specified key does not exist |
||
324 | * @return mixed|null the value of the element if found, default value otherwise |
||
325 | */ |
||
326 | 216 | public static function remove(&$array, $key, $default = null) |
|
327 | { |
||
328 | 216 | if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array))) { |
|
329 | 46 | $value = $array[$key]; |
|
330 | 46 | unset($array[$key]); |
|
331 | |||
332 | 46 | return $value; |
|
333 | } |
||
334 | |||
335 | 208 | return $default; |
|
336 | } |
||
337 | |||
338 | /** |
||
339 | * Removes items with matching values from the array and returns the removed items. |
||
340 | * |
||
341 | * Example, |
||
342 | * |
||
343 | * ```php |
||
344 | * $array = ['Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', 'Janet' => 'Jackson']; |
||
345 | * $removed = \yii\helpers\ArrayHelper::removeValue($array, 'Jackson'); |
||
346 | * // result: |
||
347 | * // $array = ['Bob' => 'Dylan', 'Mick' => 'Jagger']; |
||
348 | * // $removed = ['Michael' => 'Jackson', 'Janet' => 'Jackson']; |
||
349 | * ``` |
||
350 | * |
||
351 | * @param array $array the array where to look the value from |
||
352 | * @param string $value the value to remove from the array |
||
353 | * @return array the items that were removed from the array |
||
354 | * @since 2.0.11 |
||
355 | */ |
||
356 | 2 | public static function removeValue(&$array, $value) |
|
357 | { |
||
358 | 2 | $result = []; |
|
359 | 2 | if (is_array($array)) { |
|
0 ignored issues
–
show
introduced
by
![]() |
|||
360 | 2 | foreach ($array as $key => $val) { |
|
361 | 2 | if ($val === $value) { |
|
362 | 1 | $result[$key] = $val; |
|
363 | 2 | unset($array[$key]); |
|
364 | } |
||
365 | } |
||
366 | } |
||
367 | |||
368 | 2 | return $result; |
|
369 | } |
||
370 | |||
371 | /** |
||
372 | * Indexes and/or groups the array according to a specified key. |
||
373 | * The input should be either multidimensional array or an array of objects. |
||
374 | * |
||
375 | * The $key can be either a key name of the sub-array, a property name of object, or an anonymous |
||
376 | * function that must return the value that will be used as a key. |
||
377 | * |
||
378 | * $groups is an array of keys, that will be used to group the input array into one or more sub-arrays based |
||
379 | * on keys specified. |
||
380 | * |
||
381 | * If the `$key` is specified as `null` or a value of an element corresponding to the key is `null` in addition |
||
382 | * to `$groups` not specified then the element is discarded. |
||
383 | * |
||
384 | * For example: |
||
385 | * |
||
386 | * ```php |
||
387 | * $array = [ |
||
388 | * ['id' => '123', 'data' => 'abc', 'device' => 'laptop'], |
||
389 | * ['id' => '345', 'data' => 'def', 'device' => 'tablet'], |
||
390 | * ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'], |
||
391 | * ]; |
||
392 | * $result = ArrayHelper::index($array, 'id'); |
||
393 | * ``` |
||
394 | * |
||
395 | * The result will be an associative array, where the key is the value of `id` attribute |
||
396 | * |
||
397 | * ```php |
||
398 | * [ |
||
399 | * '123' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop'], |
||
400 | * '345' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'] |
||
401 | * // The second element of an original array is overwritten by the last element because of the same id |
||
402 | * ] |
||
403 | * ``` |
||
404 | * |
||
405 | * An anonymous function can be used in the grouping array as well. |
||
406 | * |
||
407 | * ```php |
||
408 | * $result = ArrayHelper::index($array, function ($element) { |
||
409 | * return $element['id']; |
||
410 | * }); |
||
411 | * ``` |
||
412 | * |
||
413 | * Passing `id` as a third argument will group `$array` by `id`: |
||
414 | * |
||
415 | * ```php |
||
416 | * $result = ArrayHelper::index($array, null, 'id'); |
||
417 | * ``` |
||
418 | * |
||
419 | * The result will be a multidimensional array grouped by `id` on the first level, by `device` on the second level |
||
420 | * and indexed by `data` on the third level: |
||
421 | * |
||
422 | * ```php |
||
423 | * [ |
||
424 | * '123' => [ |
||
425 | * ['id' => '123', 'data' => 'abc', 'device' => 'laptop'] |
||
426 | * ], |
||
427 | * '345' => [ // all elements with this index are present in the result array |
||
428 | * ['id' => '345', 'data' => 'def', 'device' => 'tablet'], |
||
429 | * ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'], |
||
430 | * ] |
||
431 | * ] |
||
432 | * ``` |
||
433 | * |
||
434 | * The anonymous function can be used in the array of grouping keys as well: |
||
435 | * |
||
436 | * ```php |
||
437 | * $result = ArrayHelper::index($array, 'data', [function ($element) { |
||
438 | * return $element['id']; |
||
439 | * }, 'device']); |
||
440 | * ``` |
||
441 | * |
||
442 | * The result will be a multidimensional array grouped by `id` on the first level, by the `device` on the second one |
||
443 | * and indexed by the `data` on the third level: |
||
444 | * |
||
445 | * ```php |
||
446 | * [ |
||
447 | * '123' => [ |
||
448 | * 'laptop' => [ |
||
449 | * 'abc' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop'] |
||
450 | * ] |
||
451 | * ], |
||
452 | * '345' => [ |
||
453 | * 'tablet' => [ |
||
454 | * 'def' => ['id' => '345', 'data' => 'def', 'device' => 'tablet'] |
||
455 | * ], |
||
456 | * 'smartphone' => [ |
||
457 | * 'hgi' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'] |
||
458 | * ] |
||
459 | * ] |
||
460 | * ] |
||
461 | * ``` |
||
462 | * |
||
463 | * @param array $array the array that needs to be indexed or grouped |
||
464 | * @param string|\Closure|null $key the column name or anonymous function which result will be used to index the array |
||
465 | * @param string|string[]|\Closure[]|null $groups the array of keys, that will be used to group the input array |
||
466 | * by one or more keys. If the $key attribute or its value for the particular element is null and $groups is not |
||
467 | * defined, the array element will be discarded. Otherwise, if $groups is specified, array element will be added |
||
468 | * to the result array without any key. This parameter is available since version 2.0.8. |
||
469 | * @return array the indexed and/or grouped array |
||
470 | */ |
||
471 | 428 | public static function index($array, $key, $groups = []) |
|
472 | { |
||
473 | 428 | $result = []; |
|
474 | 428 | $groups = (array) $groups; |
|
475 | |||
476 | 428 | foreach ($array as $element) { |
|
477 | 419 | $lastArray = &$result; |
|
478 | |||
479 | 419 | foreach ($groups as $group) { |
|
480 | 386 | $value = static::getValue($element, $group); |
|
481 | 386 | if (!array_key_exists($value, $lastArray)) { |
|
482 | 386 | $lastArray[$value] = []; |
|
483 | } |
||
484 | 386 | $lastArray = &$lastArray[$value]; |
|
485 | } |
||
486 | |||
487 | 419 | if ($key === null) { |
|
488 | 387 | if (!empty($groups)) { |
|
489 | 387 | $lastArray[] = $element; |
|
490 | } |
||
491 | } else { |
||
492 | 34 | $value = static::getValue($element, $key); |
|
493 | 34 | if ($value !== null) { |
|
494 | 34 | if (is_float($value)) { |
|
495 | 1 | $value = StringHelper::floatToString($value); |
|
496 | } |
||
497 | 34 | $lastArray[$value] = $element; |
|
498 | } |
||
499 | } |
||
500 | 419 | unset($lastArray); |
|
501 | } |
||
502 | |||
503 | 428 | return $result; |
|
504 | } |
||
505 | |||
506 | /** |
||
507 | * Returns the values of a specified column in an array. |
||
508 | * The input array should be multidimensional or an array of objects. |
||
509 | * |
||
510 | * For example, |
||
511 | * |
||
512 | * ```php |
||
513 | * $array = [ |
||
514 | * ['id' => '123', 'data' => 'abc'], |
||
515 | * ['id' => '345', 'data' => 'def'], |
||
516 | * ]; |
||
517 | * $result = ArrayHelper::getColumn($array, 'id'); |
||
518 | * // the result is: ['123', '345'] |
||
519 | * |
||
520 | * // using anonymous function |
||
521 | * $result = ArrayHelper::getColumn($array, function ($element) { |
||
522 | * return $element['id']; |
||
523 | * }); |
||
524 | * ``` |
||
525 | * |
||
526 | * @param array $array |
||
527 | * @param int|string|array|\Closure $name |
||
528 | * @param bool $keepKeys whether to maintain the array keys. If false, the resulting array |
||
529 | * will be re-indexed with integers. |
||
530 | * @return array the list of column values |
||
531 | */ |
||
532 | 474 | public static function getColumn($array, $name, $keepKeys = true) |
|
533 | { |
||
534 | 474 | $result = []; |
|
535 | 474 | if ($keepKeys) { |
|
536 | 474 | foreach ($array as $k => $element) { |
|
537 | 474 | $result[$k] = static::getValue($element, $name); |
|
538 | } |
||
539 | } else { |
||
540 | 1 | foreach ($array as $element) { |
|
541 | 1 | $result[] = static::getValue($element, $name); |
|
542 | } |
||
543 | } |
||
544 | |||
545 | 474 | return $result; |
|
546 | } |
||
547 | |||
548 | /** |
||
549 | * Builds a map (key-value pairs) from a multidimensional array or an array of objects. |
||
550 | * The `$from` and `$to` parameters specify the key names or property names to set up the map. |
||
551 | * Optionally, one can further group the map according to a grouping field `$group`. |
||
552 | * |
||
553 | * For example, |
||
554 | * |
||
555 | * ```php |
||
556 | * $array = [ |
||
557 | * ['id' => '123', 'name' => 'aaa', 'class' => 'x'], |
||
558 | * ['id' => '124', 'name' => 'bbb', 'class' => 'x'], |
||
559 | * ['id' => '345', 'name' => 'ccc', 'class' => 'y'], |
||
560 | * ]; |
||
561 | * |
||
562 | * $result = ArrayHelper::map($array, 'id', 'name'); |
||
563 | * // the result is: |
||
564 | * // [ |
||
565 | * // '123' => 'aaa', |
||
566 | * // '124' => 'bbb', |
||
567 | * // '345' => 'ccc', |
||
568 | * // ] |
||
569 | * |
||
570 | * $result = ArrayHelper::map($array, 'id', 'name', 'class'); |
||
571 | * // the result is: |
||
572 | * // [ |
||
573 | * // 'x' => [ |
||
574 | * // '123' => 'aaa', |
||
575 | * // '124' => 'bbb', |
||
576 | * // ], |
||
577 | * // 'y' => [ |
||
578 | * // '345' => 'ccc', |
||
579 | * // ], |
||
580 | * // ] |
||
581 | * ``` |
||
582 | * |
||
583 | * @param array $array |
||
584 | * @param string|\Closure $from |
||
585 | * @param string|\Closure $to |
||
586 | * @param string|\Closure $group |
||
587 | * @return array |
||
588 | */ |
||
589 | 109 | public static function map($array, $from, $to, $group = null) |
|
590 | { |
||
591 | 109 | $result = []; |
|
592 | 109 | foreach ($array as $element) { |
|
593 | 102 | $key = static::getValue($element, $from); |
|
594 | 102 | $value = static::getValue($element, $to); |
|
595 | 102 | if ($group !== null) { |
|
596 | 1 | $result[static::getValue($element, $group)][$key] = $value; |
|
597 | } else { |
||
598 | 102 | $result[$key] = $value; |
|
599 | } |
||
600 | } |
||
601 | |||
602 | 109 | return $result; |
|
603 | } |
||
604 | |||
605 | /** |
||
606 | * Checks if the given array contains the specified key. |
||
607 | * This method enhances the `array_key_exists()` function by supporting case-insensitive |
||
608 | * key comparison. |
||
609 | * @param string $key the key to check |
||
610 | * @param array|ArrayAccess $array the array with keys to check |
||
611 | * @param bool $caseSensitive whether the key comparison should be case-sensitive |
||
612 | * @return bool whether the array contains the specified key |
||
613 | */ |
||
614 | 702 | public static function keyExists($key, $array, $caseSensitive = true) |
|
615 | { |
||
616 | 702 | if ($caseSensitive) { |
|
617 | // Function `isset` checks key faster but skips `null`, `array_key_exists` handles this case |
||
618 | // https://secure.php.net/manual/en/function.array-key-exists.php#107786 |
||
619 | 701 | if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array))) { |
|
620 | 595 | return true; |
|
621 | } |
||
622 | // Cannot use `array_has_key` on Objects for PHP 7.4+, therefore we need to check using [[ArrayAccess::offsetExists()]] |
||
623 | 140 | return $array instanceof ArrayAccess && $array->offsetExists($key); |
|
624 | } |
||
625 | |||
626 | 2 | if ($array instanceof ArrayAccess) { |
|
627 | 1 | throw new InvalidArgumentException('Second parameter($array) cannot be ArrayAccess in case insensitive mode'); |
|
628 | } |
||
629 | |||
630 | 1 | foreach (array_keys($array) as $k) { |
|
631 | 1 | if (strcasecmp($key, $k) === 0) { |
|
632 | 1 | return true; |
|
633 | } |
||
634 | } |
||
635 | |||
636 | 1 | return false; |
|
637 | } |
||
638 | |||
639 | /** |
||
640 | * Sorts an array of objects or arrays (with the same structure) by one or several keys. |
||
641 | * @param array $array the array to be sorted. The array will be modified after calling this method. |
||
642 | * @param string|\Closure|array $key the key(s) to be sorted by. This refers to a key name of the sub-array |
||
643 | * elements, a property name of the objects, or an anonymous function returning the values for comparison |
||
644 | * purpose. The anonymous function signature should be: `function($item)`. |
||
645 | * To sort by multiple keys, provide an array of keys here. |
||
646 | * @param int|array $direction the sorting direction. It can be either `SORT_ASC` or `SORT_DESC`. |
||
647 | * When sorting by multiple keys with different sorting directions, use an array of sorting directions. |
||
648 | * @param int|array $sortFlag the PHP sort flag. Valid values include |
||
649 | * `SORT_REGULAR`, `SORT_NUMERIC`, `SORT_STRING`, `SORT_LOCALE_STRING`, `SORT_NATURAL` and `SORT_FLAG_CASE`. |
||
650 | * Please refer to [PHP manual](https://secure.php.net/manual/en/function.sort.php) |
||
651 | * for more details. When sorting by multiple keys with different sort flags, use an array of sort flags. |
||
652 | * @throws InvalidArgumentException if the $direction or $sortFlag parameters do not have |
||
653 | * correct number of elements as that of $key. |
||
654 | */ |
||
655 | 65 | public static function multisort(&$array, $key, $direction = SORT_ASC, $sortFlag = SORT_REGULAR) |
|
656 | { |
||
657 | 65 | $keys = is_array($key) ? $key : [$key]; |
|
658 | 65 | if (empty($keys) || empty($array)) { |
|
659 | 1 | return; |
|
660 | } |
||
661 | 65 | $n = count($keys); |
|
662 | 65 | if (is_scalar($direction)) { |
|
663 | 58 | $direction = array_fill(0, $n, $direction); |
|
664 | 7 | } elseif (count($direction) !== $n) { |
|
665 | 1 | throw new InvalidArgumentException('The length of $direction parameter must be the same as that of $keys.'); |
|
666 | } |
||
667 | 64 | if (is_scalar($sortFlag)) { |
|
668 | 63 | $sortFlag = array_fill(0, $n, $sortFlag); |
|
669 | 2 | } elseif (count($sortFlag) !== $n) { |
|
670 | 1 | throw new InvalidArgumentException('The length of $sortFlag parameter must be the same as that of $keys.'); |
|
671 | } |
||
672 | 63 | $args = []; |
|
673 | 63 | foreach ($keys as $i => $k) { |
|
674 | 63 | $flag = $sortFlag[$i]; |
|
675 | 63 | $args[] = static::getColumn($array, $k); |
|
676 | 63 | $args[] = $direction[$i]; |
|
677 | 63 | $args[] = $flag; |
|
678 | } |
||
679 | |||
680 | // This fix is used for cases when main sorting specified by columns has equal values |
||
681 | // Without it it will lead to Fatal Error: Nesting level too deep - recursive dependency? |
||
682 | 63 | $args[] = range(1, count($array)); |
|
683 | 63 | $args[] = SORT_ASC; |
|
684 | 63 | $args[] = SORT_NUMERIC; |
|
685 | |||
686 | 63 | $args[] = &$array; |
|
687 | 63 | call_user_func_array('array_multisort', $args); |
|
688 | 63 | } |
|
689 | |||
690 | /** |
||
691 | * Encodes special characters in an array of strings into HTML entities. |
||
692 | * Only array values will be encoded by default. |
||
693 | * If a value is an array, this method will also encode it recursively. |
||
694 | * Only string values will be encoded. |
||
695 | * @param array $data data to be encoded |
||
696 | * @param bool $valuesOnly whether to encode array values only. If false, |
||
697 | * both the array keys and array values will be encoded. |
||
698 | * @param string $charset the charset that the data is using. If not set, |
||
699 | * [[\yii\base\Application::charset]] will be used. |
||
700 | * @return array the encoded data |
||
701 | * @see https://secure.php.net/manual/en/function.htmlspecialchars.php |
||
702 | */ |
||
703 | 1 | public static function htmlEncode($data, $valuesOnly = true, $charset = null) |
|
704 | { |
||
705 | 1 | if ($charset === null) { |
|
706 | 1 | $charset = Yii::$app ? Yii::$app->charset : 'UTF-8'; |
|
707 | } |
||
708 | 1 | $d = []; |
|
709 | 1 | foreach ($data as $key => $value) { |
|
710 | 1 | if (!$valuesOnly && is_string($key)) { |
|
711 | 1 | $key = htmlspecialchars($key, ENT_QUOTES | ENT_SUBSTITUTE, $charset); |
|
712 | } |
||
713 | 1 | if (is_string($value)) { |
|
714 | 1 | $d[$key] = htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, $charset); |
|
715 | 1 | } elseif (is_array($value)) { |
|
716 | 1 | $d[$key] = static::htmlEncode($value, $valuesOnly, $charset); |
|
717 | } else { |
||
718 | 1 | $d[$key] = $value; |
|
719 | } |
||
720 | } |
||
721 | |||
722 | 1 | return $d; |
|
723 | } |
||
724 | |||
725 | /** |
||
726 | * Decodes HTML entities into the corresponding characters in an array of strings. |
||
727 | * Only array values will be decoded by default. |
||
728 | * If a value is an array, this method will also decode it recursively. |
||
729 | * Only string values will be decoded. |
||
730 | * @param array $data data to be decoded |
||
731 | * @param bool $valuesOnly whether to decode array values only. If false, |
||
732 | * both the array keys and array values will be decoded. |
||
733 | * @return array the decoded data |
||
734 | * @see https://secure.php.net/manual/en/function.htmlspecialchars-decode.php |
||
735 | */ |
||
736 | 1 | public static function htmlDecode($data, $valuesOnly = true) |
|
737 | { |
||
738 | 1 | $d = []; |
|
739 | 1 | foreach ($data as $key => $value) { |
|
740 | 1 | if (!$valuesOnly && is_string($key)) { |
|
741 | 1 | $key = htmlspecialchars_decode($key, ENT_QUOTES); |
|
742 | } |
||
743 | 1 | if (is_string($value)) { |
|
744 | 1 | $d[$key] = htmlspecialchars_decode($value, ENT_QUOTES); |
|
745 | 1 | } elseif (is_array($value)) { |
|
746 | 1 | $d[$key] = static::htmlDecode($value); |
|
747 | } else { |
||
748 | 1 | $d[$key] = $value; |
|
749 | } |
||
750 | } |
||
751 | |||
752 | 1 | return $d; |
|
753 | } |
||
754 | |||
755 | /** |
||
756 | * Returns a value indicating whether the given array is an associative array. |
||
757 | * |
||
758 | * An array is associative if all its keys are strings. If `$allStrings` is false, |
||
759 | * then an array will be treated as associative if at least one of its keys is a string. |
||
760 | * |
||
761 | * Note that an empty array will NOT be considered associative. |
||
762 | * |
||
763 | * @param array $array the array being checked |
||
764 | * @param bool $allStrings whether the array keys must be all strings in order for |
||
765 | * the array to be treated as associative. |
||
766 | * @return bool whether the array is associative |
||
767 | */ |
||
768 | 501 | public static function isAssociative($array, $allStrings = true) |
|
769 | { |
||
770 | 501 | if (!is_array($array) || empty($array)) { |
|
771 | 289 | return false; |
|
772 | } |
||
773 | |||
774 | 245 | if ($allStrings) { |
|
775 | 245 | foreach ($array as $key => $value) { |
|
776 | 245 | if (!is_string($key)) { |
|
777 | 245 | return false; |
|
778 | } |
||
779 | } |
||
780 | |||
781 | 235 | return true; |
|
782 | } |
||
783 | |||
784 | 1 | foreach ($array as $key => $value) { |
|
785 | 1 | if (is_string($key)) { |
|
786 | 1 | return true; |
|
787 | } |
||
788 | } |
||
789 | |||
790 | 1 | return false; |
|
791 | } |
||
792 | |||
793 | /** |
||
794 | * Returns a value indicating whether the given array is an indexed array. |
||
795 | * |
||
796 | * An array is indexed if all its keys are integers. If `$consecutive` is true, |
||
797 | * then the array keys must be a consecutive sequence starting from 0. |
||
798 | * |
||
799 | * Note that an empty array will be considered indexed. |
||
800 | * |
||
801 | * @param array $array the array being checked |
||
802 | * @param bool $consecutive whether the array keys must be a consecutive sequence |
||
803 | * in order for the array to be treated as indexed. |
||
804 | * @return bool whether the array is indexed |
||
805 | */ |
||
806 | 7 | public static function isIndexed($array, $consecutive = false) |
|
807 | { |
||
808 | 7 | if (!is_array($array)) { |
|
809 | 1 | return false; |
|
810 | } |
||
811 | |||
812 | 7 | if (empty($array)) { |
|
813 | 1 | return true; |
|
814 | } |
||
815 | |||
816 | 7 | if ($consecutive) { |
|
817 | 1 | return array_keys($array) === range(0, count($array) - 1); |
|
818 | } |
||
819 | |||
820 | 7 | foreach ($array as $key => $value) { |
|
821 | 7 | if (!is_int($key)) { |
|
822 | 7 | return false; |
|
823 | } |
||
824 | } |
||
825 | |||
826 | 6 | return true; |
|
827 | } |
||
828 | |||
829 | /** |
||
830 | * Check whether an array or [[Traversable]] contains an element. |
||
831 | * |
||
832 | * This method does the same as the PHP function [in_array()](https://secure.php.net/manual/en/function.in-array.php) |
||
833 | * but additionally works for objects that implement the [[Traversable]] interface. |
||
834 | * @param mixed $needle The value to look for. |
||
835 | * @param array|Traversable $haystack The set of values to search. |
||
836 | * @param bool $strict Whether to enable strict (`===`) comparison. |
||
837 | * @return bool `true` if `$needle` was found in `$haystack`, `false` otherwise. |
||
838 | * @throws InvalidArgumentException if `$haystack` is neither traversable nor an array. |
||
839 | * @see https://secure.php.net/manual/en/function.in-array.php |
||
840 | * @since 2.0.7 |
||
841 | */ |
||
842 | 20 | public static function isIn($needle, $haystack, $strict = false) |
|
843 | { |
||
844 | 20 | if ($haystack instanceof Traversable) { |
|
845 | 4 | foreach ($haystack as $value) { |
|
846 | 4 | if ($needle == $value && (!$strict || $needle === $value)) { |
|
847 | 4 | return true; |
|
848 | } |
||
849 | } |
||
850 | 20 | } elseif (is_array($haystack)) { |
|
851 | 19 | return in_array($needle, $haystack, $strict); |
|
852 | } else { |
||
853 | 1 | throw new InvalidArgumentException('Argument $haystack must be an array or implement Traversable'); |
|
854 | } |
||
855 | |||
856 | 3 | return false; |
|
857 | } |
||
858 | |||
859 | /** |
||
860 | * Checks whether a variable is an array or [[Traversable]]. |
||
861 | * |
||
862 | * This method does the same as the PHP function [is_array()](https://secure.php.net/manual/en/function.is-array.php) |
||
863 | * but additionally works on objects that implement the [[Traversable]] interface. |
||
864 | * @param mixed $var The variable being evaluated. |
||
865 | * @return bool whether $var can be traversed via foreach |
||
866 | * @see https://secure.php.net/manual/en/function.is-array.php |
||
867 | * @since 2.0.8 |
||
868 | */ |
||
869 | 1090 | public static function isTraversable($var) |
|
870 | { |
||
871 | 1090 | return is_array($var) || $var instanceof Traversable; |
|
872 | } |
||
873 | |||
874 | /** |
||
875 | * Checks whether an array or [[Traversable]] is a subset of another array or [[Traversable]]. |
||
876 | * |
||
877 | * This method will return `true`, if all elements of `$needles` are contained in |
||
878 | * `$haystack`. If at least one element is missing, `false` will be returned. |
||
879 | * @param array|Traversable $needles The values that must **all** be in `$haystack`. |
||
880 | * @param array|Traversable $haystack The set of value to search. |
||
881 | * @param bool $strict Whether to enable strict (`===`) comparison. |
||
882 | * @throws InvalidArgumentException if `$haystack` or `$needles` is neither traversable nor an array. |
||
883 | * @return bool `true` if `$needles` is a subset of `$haystack`, `false` otherwise. |
||
884 | * @since 2.0.7 |
||
885 | */ |
||
886 | 6 | public static function isSubset($needles, $haystack, $strict = false) |
|
887 | { |
||
888 | 6 | if (is_array($needles) || $needles instanceof Traversable) { |
|
889 | 5 | foreach ($needles as $needle) { |
|
890 | 4 | if (!static::isIn($needle, $haystack, $strict)) { |
|
891 | 4 | return false; |
|
892 | } |
||
893 | } |
||
894 | |||
895 | 4 | return true; |
|
896 | } |
||
897 | |||
898 | 1 | throw new InvalidArgumentException('Argument $needles must be an array or implement Traversable'); |
|
899 | } |
||
900 | |||
901 | /** |
||
902 | * Filters array according to rules specified. |
||
903 | * |
||
904 | * For example: |
||
905 | * |
||
906 | * ```php |
||
907 | * $array = [ |
||
908 | * 'A' => [1, 2], |
||
909 | * 'B' => [ |
||
910 | * 'C' => 1, |
||
911 | * 'D' => 2, |
||
912 | * ], |
||
913 | * 'E' => 1, |
||
914 | * ]; |
||
915 | * |
||
916 | * $result = \yii\helpers\ArrayHelper::filter($array, ['A']); |
||
917 | * // $result will be: |
||
918 | * // [ |
||
919 | * // 'A' => [1, 2], |
||
920 | * // ] |
||
921 | * |
||
922 | * $result = \yii\helpers\ArrayHelper::filter($array, ['A', 'B.C']); |
||
923 | * // $result will be: |
||
924 | * // [ |
||
925 | * // 'A' => [1, 2], |
||
926 | * // 'B' => ['C' => 1], |
||
927 | * // ] |
||
928 | * |
||
929 | * $result = \yii\helpers\ArrayHelper::filter($array, ['B', '!B.C']); |
||
930 | * // $result will be: |
||
931 | * // [ |
||
932 | * // 'B' => ['D' => 2], |
||
933 | * // ] |
||
934 | * ``` |
||
935 | * |
||
936 | * @param array $array Source array |
||
937 | * @param array $filters Rules that define array keys which should be left or removed from results. |
||
938 | * Each rule is: |
||
939 | * - `var` - `$array['var']` will be left in result. |
||
940 | * - `var.key` = only `$array['var']['key'] will be left in result. |
||
941 | * - `!var.key` = `$array['var']['key'] will be removed from result. |
||
942 | * @return array Filtered array |
||
943 | * @since 2.0.9 |
||
944 | */ |
||
945 | 32 | public static function filter($array, $filters) |
|
946 | { |
||
947 | 32 | $result = []; |
|
948 | 32 | $excludeFilters = []; |
|
949 | |||
950 | 32 | foreach ($filters as $filter) { |
|
951 | 11 | if (!is_string($filter) && !is_int($filter)) { |
|
952 | 1 | continue; |
|
953 | } |
||
954 | |||
955 | 10 | if (is_string($filter) && strpos($filter, '!') === 0) { |
|
956 | 3 | $excludeFilters[] = substr($filter, 1); |
|
957 | 3 | continue; |
|
958 | } |
||
959 | |||
960 | 10 | $nodeValue = $array; //set $array as root node |
|
961 | 10 | $keys = explode('.', (string) $filter); |
|
962 | 10 | foreach ($keys as $key) { |
|
963 | 10 | if (!array_key_exists($key, $nodeValue)) { |
|
964 | 8 | continue 2; //Jump to next filter |
|
965 | } |
||
966 | 10 | $nodeValue = $nodeValue[$key]; |
|
967 | } |
||
968 | |||
969 | //We've found a value now let's insert it |
||
970 | 10 | $resultNode = &$result; |
|
971 | 10 | foreach ($keys as $key) { |
|
972 | 10 | if (!array_key_exists($key, $resultNode)) { |
|
973 | 10 | $resultNode[$key] = []; |
|
974 | } |
||
975 | 10 | $resultNode = &$resultNode[$key]; |
|
976 | } |
||
977 | 10 | $resultNode = $nodeValue; |
|
978 | } |
||
979 | |||
980 | 32 | foreach ($excludeFilters as $filter) { |
|
981 | 3 | $excludeNode = &$result; |
|
982 | 3 | $keys = explode('.', (string) $filter); |
|
983 | 3 | $numNestedKeys = count($keys) - 1; |
|
984 | 3 | foreach ($keys as $i => $key) { |
|
985 | 3 | if (!array_key_exists($key, $excludeNode)) { |
|
986 | continue 2; //Jump to next filter |
||
987 | } |
||
988 | |||
989 | 3 | if ($i < $numNestedKeys) { |
|
990 | 3 | $excludeNode = &$excludeNode[$key]; |
|
991 | } else { |
||
992 | 3 | unset($excludeNode[$key]); |
|
993 | 3 | break; |
|
994 | } |
||
995 | } |
||
996 | } |
||
997 | |||
998 | 32 | return $result; |
|
999 | } |
||
1000 | } |
||
1001 |