-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArray_Extra.php
84 lines (66 loc) · 2.19 KB
/
Array_Extra.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
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
<?php //phpcs:disable Squiz.Commenting
namespace XWP\Helper\Functions;
class Array_Extra {
final public static function mergemap( callable $callback, array $arr ): array {
$result = array();
foreach ( $arr as $value ) {
$mapped = $callback( $value );
if ( ! \is_array( $mapped ) ) {
continue;
}
$result[] = $mapped;
}
return \array_merge( ...\array_values( \array_filter( $result ) ) );
}
final public static function rekey( array $arr, string $key ): array {
$result = array();
foreach ( $arr as $item ) {
if ( ! isset( $item[ $key ] ) ) {
continue; // Skip items without the key
}
$new = $item[ $key ];
unset( $item[ $key ] ); // Remove the key
$result[ $new ] = $item;
}
return $result;
}
final public static function flatmap( callable $callback, $arr ): array {
$res = array();
foreach ( $arr as $v ) {
$mapped = $callback( $v );
$res[] = (array) $mapped;
}
return \array_merge( ...$res );
}
final public static function diff_assoc( array $input_array, array $keys ): array {
return $keys
? \array_diff_key( $input_array, \array_flip( $keys ) )
: $input_array;
}
/**
* Slice the array
*
* @template TArr of array
* @template TKey of string
*
* @param TArr $input_array The input array.
* @param array<int,TKey> $keys The keys to extract.
* @return TArr
*/
final public static function slice_assoc( array $input_array, array $keys ): array {
return $keys
? \array_intersect_key( $input_array, \array_flip( $keys ) )
: $input_array;
}
final public static function from_string( string|array $target, string $delim ): array {
if ( \is_array( $target ) ) {
return $target;
}
return \array_values(
\array_filter(
\array_map( 'trim', \explode( $delim, $target ) ),
static fn( $v ) => '' !== $v,
),
);
}
}