Commit 53457a0a by Qiang Xue

Simplified ArrayHelper::multisort().

parent 52bf6ac4
......@@ -339,13 +339,10 @@ class BaseArrayHelper
* `SORT_REGULAR`, `SORT_NUMERIC`, `SORT_STRING`, `SORT_LOCALE_STRING`, `SORT_NATURAL` and `SORT_FLAG_CASE`.
* Please refer to [PHP manual](http://php.net/manual/en/function.sort.php)
* for more details. When sorting by multiple keys with different sort flags, use an array of sort flags.
* @param boolean|array $caseSensitive whether to sort string in case-sensitive manner. This parameter
* is used only when `$sortFlag` is `SORT_STRING`.
* When sorting by multiple keys with different case sensitivities, use an array of boolean values.
* @throws InvalidParamException if the $descending or $sortFlag parameters do not have
* correct number of elements as that of $key.
*/
public static function multisort(&$array, $key, $direction = SORT_ASC, $sortFlag = SORT_REGULAR, $caseSensitive = true)
public static function multisort(&$array, $key, $direction = SORT_ASC, $sortFlag = SORT_REGULAR)
{
$keys = is_array($key) ? $key : [$key];
if (empty($keys) || empty($array)) {
......@@ -362,21 +359,10 @@ class BaseArrayHelper
} elseif (count($sortFlag) !== $n) {
throw new InvalidParamException('The length of $sortFlag parameter must be the same as that of $keys.');
}
if (is_scalar($caseSensitive)) {
$caseSensitive = array_fill(0, $n, $caseSensitive);
} elseif (count($caseSensitive) !== $n) {
throw new InvalidParamException('The length of $caseSensitive parameter must be the same as that of $keys.');
}
$args = [];
foreach ($keys as $i => $key) {
$flag = $sortFlag[$i];
$cs = $caseSensitive[$i];
if (!$cs && ($flag === SORT_STRING)) {
$flag = $flag | SORT_FLAG_CASE;
$args[] = static::getColumn($array, $key);
} else {
$args[] = static::getColumn($array, $key);
}
$args[] = $direction[$i];
$args[] = $flag;
}
......
......@@ -129,13 +129,13 @@ class ArrayHelperTest extends TestCase
['name' => 'A', 'age' => 1],
];
ArrayHelper::multisort($array, ['name', 'age'], false, [SORT_STRING, SORT_REGULAR]);
ArrayHelper::multisort($array, ['name', 'age'], SORT_ASC, [SORT_STRING, SORT_REGULAR]);
$this->assertEquals(['name' => 'A', 'age' => 1], $array[0]);
$this->assertEquals(['name' => 'B', 'age' => 4], $array[1]);
$this->assertEquals(['name' => 'a', 'age' => 3], $array[2]);
$this->assertEquals(['name' => 'b', 'age' => 2], $array[3]);
ArrayHelper::multisort($array, ['name', 'age'], false, [SORT_STRING, SORT_REGULAR], false);
ArrayHelper::multisort($array, ['name', 'age'], SORT_ASC, [SORT_STRING | SORT_FLAG_CASE, SORT_REGULAR]);
$this->assertEquals(['name' => 'A', 'age' => 1], $array[0]);
$this->assertEquals(['name' => 'a', 'age' => 3], $array[1]);
$this->assertEquals(['name' => 'b', 'age' => 2], $array[2]);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment