-
-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathArrayHelper.php
More file actions
1493 lines (1381 loc) · 50.7 KB
/
ArrayHelper.php
File metadata and controls
1493 lines (1381 loc) · 50.7 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace Yiisoft\Arrays;
use Closure;
use InvalidArgumentException;
use Throwable;
use Yiisoft\Strings\NumericHelper;
use Yiisoft\Strings\StringHelper;
use function array_column;
use function array_combine;
use function array_key_exists;
use function array_keys;
use function array_merge;
use function array_pop;
use function array_search;
use function array_shift;
use function count;
use function end;
use function explode;
use function get_object_vars;
use function gettype;
use function htmlspecialchars;
use function htmlspecialchars_decode;
use function in_array;
use function is_array;
use function is_float;
use function is_int;
use function is_object;
use function is_string;
use function str_ends_with;
use function strcasecmp;
use function substr;
/**
* Yii array helper provides static methods allowing you to deal with arrays more efficiently.
*
* @psalm-type ArrayKey = float|int|string|array<array-key,float|int|string>
* @psalm-type ArrayPath = float|int|string|array<array-key,float|int|string|array<array-key,float|int|string>>
*/
final class ArrayHelper
{
/**
* Converts an object or an array of objects into an array.
*
* For example:
*
* ```php
* [
* Post::class => [
* 'id',
* 'title',
* 'createTime' => 'created_at',
* 'length' => function ($post) {
* return strlen($post->content);
* },
* ],
* ]
* ```
*
* The result of `ArrayHelper::toArray($post, $properties)` could be like the following:
*
* ```php
* [
* 'id' => 123,
* 'title' => 'test',
* 'createTime' => '2013-01-01 12:00AM',
* 'length' => 301,
* ]
* ```
*
* @param mixed $object The object to be converted into an array.
*
* It is possible to provide default way of converting an object to an array for a specific class by implementing
* {@see ArrayableInterface} in its class.
* @param array $properties A mapping from object class names to the properties that need to put into
* the resulting arrays. The properties specified for each class is an array of the following format:
*
* - A field name to include as is.
* - A key-value pair of desired array key name and model column name to take value from.
* - A key-value pair of desired array key name and a callback which returns value.
* @param bool $recursive Whether to recursively convert properties which are objects into arrays.
*
* @return array The array representation of the object.
*/
public static function toArray(mixed $object, array $properties = [], bool $recursive = true): array
{
if (is_array($object)) {
if ($recursive) {
foreach ($object as $key => $value) {
if (is_array($value) || is_object($value)) {
$object[$key] = self::toArray($value, $properties);
}
}
}
return $object;
}
if (is_object($object)) {
if (!empty($properties)) {
$className = $object::class;
if (!empty($properties[$className])) {
$result = [];
/**
* @var int|string $key
* @var string $name
*/
foreach ($properties[$className] as $key => $name) {
if (is_int($key)) {
$result[$name] = $object->$name;
} else {
$result[$key] = self::getValue($object, $name);
}
}
return $recursive ? self::toArray($result, $properties) : $result;
}
}
if ($object instanceof ArrayableInterface) {
$result = $object->toArray([], [], $recursive);
} else {
$result = [];
/**
* @var string $key
*/
foreach ($object as $key => $value) {
$result[$key] = $value;
}
}
return $recursive ? self::toArray($result, $properties) : $result;
}
return [$object];
}
/**
* Merges two or more arrays into one recursively. If each array has an element with the same string key value,
* the latter will overwrite the former (different from {@see array_merge_recursive()}). Recursive merging will be
* conducted if both arrays have an element of array type and are having the same key. For integer-keyed elements,
* the elements from the latter array will be appended to the former array.
*
* @param array ...$arrays Arrays to be merged.
*
* @return array The merged array (the original arrays are not changed).
*/
public static function merge(...$arrays): array
{
return self::doMerge($arrays, null);
}
/**
* Merges two or more arrays into one recursively with specified depth. If each array has an element with the same
* string key value, the latter will overwrite the former (different from {@see array_merge_recursive()}).
* Recursive merging will be conducted if both arrays have an element of array type and are having the same key.
* For integer-keyed elements, the elements from the latter array will be appended to the former array.
*
* @param array[] $arrays Arrays to be merged.
* @param int|null $depth The maximum depth that for recursive merging. `Null` means unlimited depth.
*
* @return array The merged array (the original arrays are not changed).
*/
public static function parametrizedMerge(array $arrays, ?int $depth): array
{
return self::doMerge($arrays, $depth);
}
/**
* Retrieves the value of an array element or object property with the given key or property name.
* If the key does not exist in the array or object, the default value will be returned instead.
*
* Below are some usage examples,
*
* ```php
* // Working with an array:
* $username = \Yiisoft\Arrays\ArrayHelper::getValue($_POST, 'username');
*
* // Working with an object:
* $username = \Yiisoft\Arrays\ArrayHelper::getValue($user, 'username');
*
* // Working with anonymous function:
* $fullName = \Yiisoft\Arrays\ArrayHelper::getValue($user, function ($user, $defaultValue) {
* return $user->firstName . ' ' . $user->lastName;
* });
*
* // Using an array of keys to retrieve the value:
* $value = \Yiisoft\Arrays\ArrayHelper::getValue($versions, ['1.0', 'date']);
* ```
*
* @param array|object $array Array or object to extract value from.
* @param array|Closure|float|int|string $key Key name of the array element,
* an array of keys, object property name, object method like `getName()`, or an anonymous function
* returning the value. The anonymous function signature should be:
* `function($array, $defaultValue)`.
* @param mixed $default The default value to be returned if the specified array key does not exist. Not used when
* getting value from an object.
*
* @psalm-param ArrayKey|Closure $key
*
* @return mixed The value of the element if found, default value otherwise.
*/
public static function getValue(
array|object $array,
array|Closure|float|int|string $key,
mixed $default = null
): mixed {
if ($key instanceof Closure) {
return $key($array, $default);
}
if (is_array($array) && is_scalar($key)) {
return array_key_exists($key, $array) ? $array[$key] : $default;
}
if (is_array($key)) {
if (empty($key)) {
return $default;
}
$lastKey = array_pop($key);
foreach ($key as $keyPart) {
$array = self::getRootValue($array, $keyPart, null);
if (!is_array($array) && !is_object($array)) {
return $default;
}
}
return self::getRootValue($array, $lastKey, $default);
}
return self::getRootValue($array, $key, $default);
}
/**
* @param mixed $array Array or object to extract value from, otherwise method will return $default.
* @param float|int|string $key Key name of the array element, object property name or object method like `getValue()`.
* @param mixed $default The default value to be returned if the specified array key does not exist. Not used when
* getting value from an object.
*
* @return mixed The value of the element if found, default value otherwise.
*/
private static function getRootValue(mixed $array, float|int|string $key, mixed $default): mixed
{
if (is_array($array)) {
$key = self::normalizeArrayKey($key);
return array_key_exists($key, $array) ? $array[$key] : $default;
}
if (is_object($array)) {
$key = (string) $key;
if (str_ends_with($key, '()')) {
$method = substr($key, 0, -2);
/** @psalm-suppress MixedMethodCall */
return $array->$method();
}
try {
/** @psalm-suppress MixedPropertyFetch */
return $array::$$key;
} catch (Throwable) {
/**
* This is expected to fail if the property does not exist, or __get() is not implemented.
* It is not reliably possible to check whether a property is accessible beforehand.
*
* @psalm-suppress MixedPropertyFetch
*/
return $array->$key;
}
}
return $default;
}
/**
* Retrieves the value of an array element or object property with the given key or property name.
* If the key does not exist in the array or object, the default value will be returned instead.
*
* The key may be specified in a dot-separated format to retrieve the value of a subarray or the property
* of an embedded object. In particular, if the key is `x.y.z`, then the returned value would
* be `$array['x']['y']['z']` or `$array->x->y->z` (if `$array` is an object). If `$array['x']`
* or `$array->x` is neither an array nor an object, the default value will be returned.
* Note that if the array already has an element `x.y.z`, then its value will be returned
* instead of going through the subarrays. So it is better to be done specifying an array of key names
* like `['x', 'y', 'z']`.
*
* Below are some usage examples,
*
* ```php
* // Using separated format to retrieve the property of embedded object:
* $street = \Yiisoft\Arrays\ArrayHelper::getValue($users, 'address.street');
*
* // Using an array of keys to retrieve the value:
* $value = \Yiisoft\Arrays\ArrayHelper::getValue($versions, ['1.0', 'date']);
* ```
*
* @param array|object $array Array or object to extract value from.
* @param array|Closure|float|int|string $path Key name of the array element, an array of keys or property name
* of the object, or an anonymous function returning the value. The anonymous function signature should be:
* `function($array, $defaultValue)`.
* @param mixed $default The default value to be returned if the specified array key does not exist. Not used when
* getting value from an object.
* @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
* to "." (dot).
*
* @psalm-param ArrayPath|Closure $path
*
* @return mixed The value of the element if found, default value otherwise.
*/
public static function getValueByPath(
array|object $array,
array|Closure|float|int|string $path,
mixed $default = null,
string $delimiter = '.'
): mixed {
return self::getValue(
$array,
$path instanceof Closure ? $path : self::parseMixedPath($path, $delimiter),
$default
);
}
/**
* Writes a value into an associative array at the key path specified.
* If there is no such key path yet, it will be created recursively.
* If the key exists, it will be overwritten.
*
* ```php
* $array = [
* 'key' => [
* 'in' => [
* 'val1',
* 'key' => 'val'
* ]
* ]
* ];
* ```
*
* The result of `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
* will be the following:
*
* ```php
* [
* 'key' => [
* 'in' => [
* 'arr' => 'val'
* ]
* ]
* ]
* ```
*
* @param array $array The array to write the value to.
* @param array|float|int|string|null $key The path of where do you want to write a value to `$array`
* the path can be described by an array of keys. If the path is `null` then `$array` will be assigned the `$value`.
*
* @psalm-param ArrayKey|null $key
*
* @param mixed $value The value to be written.
*/
public static function setValue(array &$array, array|float|int|string|null $key, mixed $value): void
{
if ($key === null) {
$array = $value;
return;
}
$keys = is_array($key) ? $key : [$key];
while (count($keys) > 1) {
$k = self::normalizeArrayKey(array_shift($keys));
if (!isset($array[$k])) {
$array[$k] = [];
}
if (!is_array($array[$k])) {
$array[$k] = [$array[$k]];
}
$array = &$array[$k];
/** @var array $array */
}
$array[self::normalizeArrayKey(array_shift($keys))] = $value;
}
/**
* Find array value in an array at the key path specified and add passed value to him.
*
* If there is no such key path yet, it will be created recursively and an empty array will be initialized.
*
* ```php
* $array = ['key' => []];
*
* ArrayHelper::addValue($array, ['key', 'in'], 'variable1');
* ArrayHelper::addValue($array, ['key', 'in'], 'variable2');
*
* // Result: ['key' => ['in' => ['variable1', 'variable2']]]
* ```
*
* If the value exists, it will become the first element of the array.
*
* ```php
* $array = ['key' => 'in'];
*
* ArrayHelper::addValue($array, ['key'], 'variable1');
*
* // Result: ['key' => ['in', 'variable1']]
* ```
*
* @param array $array The array to append the value to.
* @param array|float|int|string|null $key The path of where do you want to append a value to `$array`. The path can
* be described by an array of keys. If the path is `null` then `$value` will be appended to the `$array`.
*
* @psalm-param ArrayKey|null $key
*
* @param mixed $value The value to be appended.
*/
public static function addValue(array &$array, array|float|int|string|null $key, mixed $value): void
{
if ($key === null) {
$array[] = $value;
return;
}
$keys = is_array($key) ? $key : [$key];
while (count($keys) > 0) {
$k = self::normalizeArrayKey(array_shift($keys));
if (!array_key_exists($k, $array)) {
$array[$k] = [];
} elseif (!is_array($array[$k])) {
$array[$k] = [$array[$k]];
}
$array = &$array[$k];
/** @var array $array */
}
$array[] = $value;
}
/**
* Find array value in an array at the key path specified and add passed value to him.
*
* @see addValue
*
* @param array $array The array to append the value to.
* @param array|float|int|string|null $path The path of where do you want to append a value to `$array`. The path
* can be described by a string when each key should be separated by a dot. You can also describe the path as
* an array of keys. If the path is `null` then `$value` will be appended to the `$array`.
* @param mixed $value The value to be added.
* @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
* to "." (dot).
*
* @psalm-param ArrayPath|null $path
*/
public static function addValueByPath(
array &$array,
array|float|int|string|null $path,
mixed $value,
string $delimiter = '.'
): void {
self::addValue($array, $path === null ? null : self::parseMixedPath($path, $delimiter), $value);
}
/**
* Writes a value into an associative array at the key path specified.
* If there is no such key path yet, it will be created recursively.
* If the key exists, it will be overwritten.
*
* ```php
* $array = [
* 'key' => [
* 'in' => [
* 'val1',
* 'key' => 'val'
* ]
* ]
* ];
* ```
*
* The result of `ArrayHelper::setValue($array, 'key.in.0', ['arr' => 'val']);` will be the following:
*
* ```php
* [
* 'key' => [
* 'in' => [
* ['arr' => 'val'],
* 'key' => 'val'
* ]
* ]
* ]
*
* ```
*
* The result of
* `ArrayHelper::setValue($array, 'key.in', ['arr' => 'val']);` or
* `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
* will be the following:
*
* ```php
* [
* 'key' => [
* 'in' => [
* 'arr' => 'val'
* ]
* ]
* ]
* ```
*
* @param array $array The array to write the value to.
* @param array|float|int|string|null $path The path of where do you want to write a value to `$array`.
* The path can be described by a string when each key should be separated by a delimiter (default is dot).
* You can also describe the path as an array of keys. If the path is `null` then `$array` will be assigned
* the `$value`.
* @param mixed $value The value to be written.
* @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
* to "." (dot).
*
* @psalm-param ArrayPath|null $path
*/
public static function setValueByPath(
array &$array,
array|float|int|string|null $path,
mixed $value,
string $delimiter = '.'
): void {
self::setValue($array, $path === null ? null : self::parseMixedPath($path, $delimiter), $value);
}
/**
* Removes an item from an array and returns the value. If the key does not exist in the array, the default value
* will be returned instead.
*
* Usage examples,
*
* ```php
* // $array = ['type' => 'A', 'options' => [1, 2]];
*
* // Working with an array:
* $type = \Yiisoft\Arrays\ArrayHelper::remove($array, 'type');
*
* // $array content
* // $array = ['options' => [1, 2]];
* ```
*
* @param array $array The array to extract value from.
* @param array|float|int|string $key Key name of the array element or associative array at the key path specified.
* @param mixed $default The default value to be returned if the specified key does not exist.
*
* @psalm-param ArrayKey $key
*
* @return mixed The value of the element if found, default value otherwise.
*/
public static function remove(array &$array, array|float|int|string $key, mixed $default = null): mixed
{
$keys = is_array($key) ? $key : [$key];
while (count($keys) > 1) {
$key = self::normalizeArrayKey(array_shift($keys));
if (!isset($array[$key]) || !is_array($array[$key])) {
return $default;
}
$array = &$array[$key];
}
$key = self::normalizeArrayKey(array_shift($keys));
if (array_key_exists($key, $array)) {
$value = $array[$key];
unset($array[$key]);
return $value;
}
return $default;
}
/**
* Removes an item from an array and returns the value. If the key does not exist in the array, the default value
* will be returned instead.
*
* Usage examples,
*
* ```php
* // $array = ['type' => 'A', 'options' => [1, 2]];
*
* // Working with an array:
* $type = \Yiisoft\Arrays\ArrayHelper::remove($array, 'type');
*
* // $array content
* // $array = ['options' => [1, 2]];
* ```
*
* @param array $array The array to extract value from.
* @param array|float|int|string $path Key name of the array element or associative array at the key path specified.
* The path can be described by a string when each key should be separated by a delimiter (default is dot).
* @param mixed $default The default value to be returned if the specified key does not exist.
* @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
* to "." (dot).
*
* @psalm-param ArrayPath $path
*
* @return mixed The value of the element if found, default value otherwise.
*/
public static function removeByPath(
array &$array,
array|float|int|string $path,
mixed $default = null,
string $delimiter = '.'
): mixed {
return self::remove($array, self::parseMixedPath($path, $delimiter), $default);
}
/**
* Removes items with matching values from the array and returns the removed items.
*
* Example,
*
* ```php
* $array = ['Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', 'Janet' => 'Jackson'];
* $removed = \Yiisoft\Arrays\ArrayHelper::removeValue($array, 'Jackson');
* // result:
* // $array = ['Bob' => 'Dylan', 'Mick' => 'Jagger'];
* // $removed = ['Michael' => 'Jackson', 'Janet' => 'Jackson'];
* ```
*
* @param array $array The array where to look the value from.
* @param mixed $value The value to remove from the array.
*
* @return array The items that were removed from the array.
*/
public static function removeValue(array &$array, mixed $value): array
{
$result = [];
foreach ($array as $key => $val) {
if ($val === $value) {
$result[$key] = $val;
unset($array[$key]);
}
}
return $result;
}
/**
* Indexes and/or groups the array according to a specified key.
* The input should be either multidimensional array or an array of objects.
*
* The `$key` can be either a key name of the subarray, a property name of an object, or an anonymous
* function that must return the value that will be used as a key.
*
* `$groups` is an array of keys that will be used to group the input array into one or more subarrays based
* on keys specified.
*
* If the `$key` is specified as `null` or a value of an element corresponding to the key is `null` in addition
* to `$groups` not specified, then the element is discarded.
*
* For example:
*
* ```php
* $array = [
* ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
* ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
* ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
* ];
* $result = ArrayHelper::index($array, 'id');
* ```
*
* The result will be an associative array, where the key is the value of `id` attribute
*
* ```php
* [
* '123' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
* '345' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
* // The second element of an original array is overwritten by the last element because of the same id
* ]
* ```
*
* An anonymous function can be used in the grouping array as well.
*
* ```php
* $result = ArrayHelper::index($array, function ($element) {
* return $element['id'];
* });
* ```
*
* Passing `id` as a third argument will group `$array` by `id`:
*
* ```php
* $result = ArrayHelper::index($array, null, 'id');
* ```
*
* The result will be a multidimensional array grouped by `id` on the first level, by `device` on the second level
* and indexed by `data` on the third level:
*
* ```php
* [
* '123' => [
* ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
* ],
* '345' => [ // all elements with this index are present in the result array
* ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
* ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
* ]
* ]
* ```
*
* The anonymous function can be used in the array of grouping keys as well:
*
* ```php
* $result = ArrayHelper::index($array, 'data', [function ($element) {
* return $element['id'];
* }, 'device']);
* ```
*
* The result will be a multidimensional array grouped by `id` on the first level, by the `device` on the second one
* and indexed by the `data` on the third level:
*
* ```php
* [
* '123' => [
* 'laptop' => [
* 'abc' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
* ]
* ],
* '345' => [
* 'tablet' => [
* 'def' => ['id' => '345', 'data' => 'def', 'device' => 'tablet']
* ],
* 'smartphone' => [
* 'hgi' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
* ]
* ]
* ]
* ```
*
* @param iterable $array The array or iterable object that needs to be indexed or grouped.
* @param Closure|string|null $key The column name or anonymous function which result will be used
* to index the array.
* @param Closure[]|string|string[]|null $groups The array of keys that will be used to group the input
* array by one or more keys. If the `$key` attribute or its value for the particular element is null and `$groups`
* is not defined, the array element will be discarded. Otherwise, if `$groups` is specified, an array element will be
* added to the result array without any key.
*
* @psalm-param iterable<mixed, array|object> $array
*
* @return array The indexed and/or grouped array.
*/
public static function index(
iterable $array,
Closure|string|null $key,
array|string|null $groups = []
): array {
$result = [];
$groups = (array)$groups;
/** @var mixed $element */
foreach ($array as $element) {
if (!is_array($element) && !is_object($element)) {
throw new InvalidArgumentException(
'index() can not get value from ' . gettype($element) .
'. The $array should be either multidimensional array or an array of objects.'
);
}
$lastArray = &$result;
foreach ($groups as $group) {
$value = self::normalizeArrayKey(
self::getValue($element, $group)
);
if (!array_key_exists($value, $lastArray)) {
$lastArray[$value] = [];
}
/** @psalm-suppress MixedAssignment */
$lastArray = &$lastArray[$value];
/** @var array $lastArray */
}
if ($key === null) {
if (!empty($groups)) {
$lastArray[] = $element;
}
} else {
$value = self::getValue($element, $key);
if ($value !== null) {
$lastArray[self::normalizeArrayKey($value)] = $element;
}
}
unset($lastArray);
}
return $result;
}
/**
* Groups the array according to a specified key.
* This is just an alias for indexing by groups
*
* @param iterable $array The array or iterable object that needs to be grouped.
* @param Closure[]|string|string[] $groups The array of keys that will be used to group the input array
* by one or more keys.
*
* @return array The grouped array.
*
* @template T as array|object
* @psalm-param iterable<mixed, T> $array
* @psalm-return array<non-empty-list<T>>
*/
public static function group(iterable $array, array|string $groups): array
{
/** @psalm-var array<non-empty-list<T>> */
return self::index($array, null, $groups);
}
/**
* Returns the values of a specified column in an array.
* The input array should be multidimensional or an array of objects.
*
* For example,
*
* ```php
* $array = [
* ['id' => '123', 'data' => 'abc'],
* ['id' => '345', 'data' => 'def'],
* ];
* $result = ArrayHelper::getColumn($array, 'id');
* // the result is: ['123', '345']
*
* // using anonymous function
* $result = ArrayHelper::getColumn($array, function ($element) {
* return $element['id'];
* });
* ```
*
* @param iterable $array The array or iterable object to get column from.
* @param Closure|string $name Column name or a closure returning column name.
* @param bool $keepKeys Whether to maintain the array keys. If false, the resulting array
* will be re-indexed with integers.
*
* @psalm-param iterable<array-key, array|object> $array
*
* @return array The list of column values.
*/
public static function getColumn(iterable $array, Closure|string $name, bool $keepKeys = true): array
{
$result = [];
if ($keepKeys) {
foreach ($array as $k => $element) {
$result[$k] = self::getValue($element, $name);
}
} else {
foreach ($array as $element) {
$result[] = self::getValue($element, $name);
}
}
return $result;
}
/**
* Builds a map (key-value pairs) from a multidimensional array or an array of objects.
* The `$from` and `$to` parameters specify the key names or property names to set up the map.
* Optionally, one can further group the map according to a grouping field `$group`.
*
* For example:
*
* ```php
* $array = [
* ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
* ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
* ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
* ];
*
* $result = ArrayHelper::map($array, 'id', 'name');
* ```
*
* The result will be an associative array, where the key is the value of `id` attribute
*
* ```php
* [
* '123' => 'aaa',
* '124' => 'bbb',
* '345' => 'ccc',
* ]
* ```
*
* $result = ArrayHelper::map($array, 'id', 'name', 'class');
* // the result is:
* // [
* // 'x' => [
* // '123' => 'aaa',
* // '124' => 'bbb',
* // ],
* // 'y' => [
* // '345' => 'ccc',
* // ],
* // ]
* ```
*
* @param iterable $array Array or iterable object to build a map from.
* @param Closure|string $from Key or property name to map from.
* @param Closure|string $to Key or property name to map to.
* @param Closure|string|null $group Key or property to group the map.
*
* @psalm-param iterable<mixed, array|object> $array
*
* @return array Resulting map.
*/
public static function map(
iterable $array,
Closure|string $from,
Closure|string $to,
Closure|string|null $group = null
): array {
if ($group === null) {
if ($from instanceof Closure || $to instanceof Closure || !is_array($array)) {
$result = [];
foreach ($array as $element) {
$key = (string)self::getValue($element, $from);
$result[$key] = self::getValue($element, $to);
}
return $result;
}
return array_column($array, $to, $from);
}
$result = [];
foreach ($array as $element) {
$groupKey = (string)self::getValue($element, $group);
$key = (string)self::getValue($element, $from);
$result[$groupKey][$key] = self::getValue($element, $to);
}
return $result;
}
/**
* Checks if the given array contains the specified key.
* This method enhances the `array_key_exists()` function by supporting case-insensitive
* key comparison.
*
* @param array $array The array with keys to check.
* @param array|float|int|string $key The key to check.
* @param bool $caseSensitive Whether the key comparison should be case-sensitive.
*
* @psalm-param ArrayKey $key
*
* @return bool Whether the array contains the specified key.
*/
public static function keyExists(array $array, array|float|int|string $key, bool $caseSensitive = true): bool
{
if (is_array($key)) {
if (empty($key)) {
return false;
}
if (count($key) === 1) {
return self::rootKeyExists($array, end($key), $caseSensitive);
}
/** @psalm-var non-empty-array<array-key,float|int|string> $key */
foreach (self::getExistsKeys($array, array_shift($key), $caseSensitive) as $existKey) {
$array = self::getRootValue($array, $existKey, null);
if (is_array($array) && self::keyExists($array, $key, $caseSensitive)) {
return true;
}
}
return false;
}
return self::rootKeyExists($array, $key, $caseSensitive);
}
private static function rootKeyExists(array $array, float|int|string $key, bool $caseSensitive): bool
{
$key = (string)$key;
if ($caseSensitive) {
return array_key_exists($key, $array);
}
foreach (array_keys($array) as $k) {
if (strcasecmp($key, (string)$k) === 0) {
return true;
}
}
return false;
}
/**
* @return array<int, array-key>
*/
private static function getExistsKeys(array $array, float|int|string $key, bool $caseSensitive): array
{