Grouping

group

Definition

1
Arr::group(array $array, string|int $key): array
Copied!

Description

Group array of arrays by value of element with specified key

Examples

1
$array = [
2
'a' => ['key1' => 'test1', 'key2' => 1, 'key3' => 'a'],
3
'b' => ['key1' => 'test1', 'key2' => 2],
4
2 => ['key1' => 'test2', 'key2' => 3, 'key3' => 'b']
5
];
6
7
Arr::group($array, 'key1') ->
8
[
9
'test1' => [
10
'a' => ['key1' => 'test1', 'key2' => 1, 'key3' => 'a'],
11
'b' => ['key1' => 'test1', 'key2' => 2]
12
],
13
'test2' => [
14
2 => ['key1' => 'test2', 'key2' => 3, 'key3' => 'b']
15
],
16
]
17
18
Arr::group($array, 'key2') ->
19
[
20
1 => [
21
'a' => ['key1' => 'test1', 'key2' => 1, 'key3' => 'a'],
22
],
23
2 => [
24
'b' => ['key1' => 'test1', 'key2' => 2]
25
],
26
3 => [
27
2 => ['key1' => 'test2', 'key2' => 3, 'key3' => 'b']
28
],
29
]
30
31
Arr::group($array, 'key3') ->
32
[
33
'a' => [
34
'a' => ['key1' => 'test1', 'key2' => 1, 'key3' => 'a']
35
],
36
'b' => [
37
2 => ['key1' => 'test2', 'key2' => 3, 'key3' => 'b']
38
],
39
]
40
41
Arr::group($array, 'key4') -> []
Copied!

groupObjects

Definition

1
Arr::groupObjects(array $objects, string $method, ...$args): array
Copied!

Description

Group array of objects by value returned from specified method

Examples

1
$object1 = new class() {
2
function test() {
3
return 'test1';
4
}
5
};
6
$object2 = new class() {
7
function test() {
8
return 'test2';
9
}
10
};
11
12
Arr::groupObjects([$object1, $object2, $object1], 'test') ->
13
[
14
'test1' => [$object1, $object1],
15
'test2' => [$object2],
16
]
17
18
// This method is also very useful in conjunction with Arr::flattenSingle to assign unique key for each object
19
Arr::flattenSingle(Arr::groupObjects([$object1, $object2], 'test')) ->
20
[
21
'test1' => $object1,
22
'test2' => $object2,
23
]
Copied!
Last modified 2yr ago
Copy link