Final Class Yiisoft\Arrays\ArraySorter
| Inheritance | Yiisoft\Arrays\ArraySorter |
|---|
Public Methods
| Method | Description | Defined By |
|---|---|---|
| multisort() | Sorts an array of objects or arrays (with the same structure) by one or several keys. | Yiisoft\Arrays\ArraySorter |
Method Details
Sorts an array of objects or arrays (with the same structure) by one or several keys.
For example:
$data = [
['age' => 30, 'name' => 'Alexander'],
['age' => 30, 'name' => 'Brian'],
['age' => 19, 'name' => 'Barney'],
];
ArraySorter::multisort($data, ['age', 'name'], [SORT_ASC, SORT_DESC]);
After sorting, we'll get the following in $data:
[
['age' => 19, 'name' => 'Barney'],
['age' => 30, 'name' => 'Brian'],
['age' => 30, 'name' => 'Alexander'],
];
| public static void multisort ( array<array-key, array|object> &$array, array<array-key, Closure|string>|Closure|string $key, array<array-key, integer>|integer $direction = SORT_ASC, array<array-key, integer>|integer $sortFlag = SORT_REGULAR ) | ||
| $array | array<array-key, array|object> |
The array to be sorted. The array will be modified after calling this method. |
| $key | array<array-key, Closure|string>|Closure|string |
The key(s) to be sorted by. This refers to a key
name of the subarray elements, a property name of the objects, or an anonymous function returning the values
for comparison purpose. The anonymous function signature should be: |
| $direction | array<array-key, integer>|integer |
The sorting direction. It can be either |
| $sortFlag | array<array-key, integer>|integer |
The PHP sort flag. Valid values include
|
| throws | InvalidArgumentException |
If the |
|---|---|---|
public static function multisort(
array &$array,
array|Closure|string $key,
array|int $direction = SORT_ASC,
array|int $sortFlag = SORT_REGULAR
): void {
$count = count($array);
if ($count === 0) {
return;
}
$keys = is_array($key) ? $key : [$key];
$keysCount = count($keys);
if ($keysCount === 0) {
return;
}
if (is_array($direction) && count($direction) !== $keysCount) {
throw new InvalidArgumentException('The length of $direction parameter must be the same as that of $keys.');
}
if (is_array($sortFlag) && count($sortFlag) !== $keysCount) {
throw new InvalidArgumentException('The length of $sortFlag parameter must be the same as that of $keys.');
}
$args = [];
for ($i = 0; $i < $keysCount; $i++) {
$args[] = ArrayHelper::getColumn($array, $keys[$i]);
$args[] = is_array($direction) ? $direction[$i] : $direction;
$args[] = is_array($sortFlag) ? $sortFlag[$i] : $sortFlag;
}
// Add tie-breaker only for non-empty arrays
if ($count > 0) {
$tieBreaker = [];
for ($i = 0; $i < $count; $i++) {
$tieBreaker[$i] = $i + 1;
}
$args[] = $tieBreaker;
$args[] = SORT_ASC;
$args[] = SORT_NUMERIC;
}
/** @psalm-suppress UnsupportedReferenceUsage */
$args[] = &$array;
/** @psalm-suppress ArgumentTypeCoercion */
array_multisort(...$args);
}
Signup or Login in order to comment.