1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Rico\Slib; |
6
|
|
|
|
7
|
|
|
abstract class ArrayUtils |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* Extracts each element of a $multidimensionalArray in a single list. |
11
|
|
|
* |
12
|
|
|
* @param array<array> $multidimensionalArray |
13
|
|
|
* |
14
|
|
|
* @return array<Object> |
15
|
|
|
*/ |
16
|
|
|
public static function flatten(array $multidimensionalArray): array |
17
|
|
|
{ |
18
|
|
|
return array_map('current', $multidimensionalArray); |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Inserts an element $needle at the $index position in the $haystack, conserving the order and moving other element in the way.\n |
23
|
|
|
* Careful, keys will not be preserved. |
24
|
|
|
* |
25
|
|
|
* @param mixed $needle |
26
|
|
|
* @param int $index |
27
|
|
|
* @param array<mixed> $haystack |
28
|
|
|
* |
29
|
|
|
* @return array<mixed> |
30
|
|
|
*/ |
31
|
|
|
public static function insert($needle, int $index, array $haystack): array |
32
|
|
|
{ |
33
|
|
|
if (($offset = array_search($index, array_keys($haystack))) === false) { |
34
|
|
|
$haystack[$index] = $needle; |
35
|
|
|
ksort($haystack); |
36
|
|
|
return $haystack; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
return array_merge(array_slice($haystack, 0, (int) $offset), [$needle], array_slice($haystack, (int) $offset)); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Extracts all $property values from a multidimensional $multidimensionalArray. |
44
|
|
|
* |
45
|
|
|
* @param array<array> $multidimensionalArray |
46
|
|
|
* @param string $property |
47
|
|
|
* |
48
|
|
|
* @return array<Object> |
49
|
|
|
*/ |
50
|
|
|
public static function pluck(array $multidimensionalArray, string $property): array |
51
|
|
|
{ |
52
|
|
|
return array_reduce($multidimensionalArray, function ($result, $currentArray) use ($property) { |
53
|
|
|
if (isset($currentArray[$property])) { |
54
|
|
|
$result[] = $currentArray[$property]; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
return $result; |
58
|
|
|
}, []); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Transforms multiple $similarArrays into key-valued arrays. |
63
|
|
|
* |
64
|
|
|
* @param array<array> $similarArrays |
65
|
|
|
* |
66
|
|
|
* @return mixed[] |
67
|
|
|
*/ |
68
|
|
|
public static function transpose(array $similarArrays): array |
69
|
|
|
{ |
70
|
|
|
$keyValuesArrays = []; |
71
|
|
|
foreach ($similarArrays as $globalKey => $currentArray) { |
72
|
|
|
if (!is_array($currentArray)) { |
73
|
|
|
continue; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
foreach ($currentArray as $currentKey => $currentValue) { |
77
|
|
|
$keyValuesArrays[$currentKey][$globalKey] = $currentValue; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
return $keyValuesArrays; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|