Sorting

orderByKeys

Definition

1
Arr::orderByKeys(array $array, mixed $keys, bool $appendUnmatched = true): array
Copied!

Description

Order associative array according to supplied keys order

Examples

1
$array = [
2
'foo',
3
'a' => 'bar',
4
'b' => 'test',
5
1,
6
'c' => ['test' => 2]
7
];
8
9
Arr::orderByKeys($array, 'a.0.c.1.b') ->
10
[
11
'a' => 'bar',
12
0 => 'foo',
13
'c' => ['test' => 2],
14
1 => 1,
15
'b' => 'test',
16
]
17
18
Arr::orderByKeys($array, 'a.0.c') ->
19
[
20
'a' => 'bar',
21
0 => 'foo',
22
'c' => ['test' => 2],
23
24
'b' => 'test',
25
1 => 1,
26
]
27
28
Arr::orderByKeys($array, 'a.0.c', false) ->
29
[
30
'a' => 'bar',
31
0 => 'foo',
32
'c' => ['test' => 2],
33
]
Copied!

sortByKeys

Definition

1
Arr::sortByKeys(array $array, mixed $keys = null, bool $assoc = true): array
Copied!

Description

Sort array of arrays using value specified by key(s)

Examples

1
$array = [
2
'a' => ['b' => ['c' => 3]],
3
'b' => ['b' => ['c' => -1]],
4
'c' => ['b' => ['c' => 0]]
5
];
6
7
Arr::sortByKeys($array, 'b.c') ->
8
[
9
'c' => ['b' => ['c' => -1]],
10
'd' => ['b' => ['c' => 0]],
11
'a' => ['b' => ['c' => 3]],
12
]
13
14
Arr::sortByKeys($array, 'b.c', false) ->
15
[
16
['b' => ['c' => -1]],
17
['b' => ['c' => 0]],
18
['b' => ['c' => 3]],
19
]
20
21
Arr::sortByKeys(['a' => 3, 'b' => 1, 'c' => 6]) -> ['b' => 1, 'a' => 3, 'c' => 6]
22
Arr::sortByKeys(['a' => 3, 'b' => 1, 'c' => 6], null, false) -> [1, 3, 6]
Copied!

sortObjects

Definition

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

Description

Sort array of objects by comparing result of supplied method name
$object1->$method(...$args) <=> $object2->$method(...$args)

Examples

1
$object1 = new class() {
2
function getValue() {
3
return 1;
4
}
5
};
6
$object2 = new class() {
7
function getValue(bool $reverse = false) {
8
return $reverse ? 1/2 : 2;
9
}
10
};
11
$object3 = new class() {
12
function getValue(bool $reverse = false) {
13
return $reverse ? 1/3 : 3;
14
}
15
};
16
17
$array = [$object2, $object3, $object1];
18
19
Arr::sortObjects($array, 'getValue') -> [$object1, $object2, $object3]
20
Arr::sortObjects($array, 'getValue', true) -> [$object3, $object2, $object1]
Copied!
Last modified 2yr ago