diff --git a/framework/util/ArrayHelper.php b/framework/util/ArrayHelper.php index 4d83b31..e068cbf 100644 --- a/framework/util/ArrayHelper.php +++ b/framework/util/ArrayHelper.php @@ -243,7 +243,7 @@ class ArrayHelper * @throws \yii\base\BadParamException if the $ascending or $sortFlag parameters do not have * correct number of elements as that of $key. */ - public static function sort(&$array, $key, $ascending = true, $sortFlag = SORT_REGULAR) + public static function multisort(&$array, $key, $ascending = true, $sortFlag = SORT_REGULAR) { $keys = is_array($key) ? $key : array($key); if (empty($keys) || empty($array)) { @@ -273,10 +273,10 @@ class ArrayHelper } else { $args[] = static::getColumn($array, $key); } - $args[] = $ascending[$i]; + $args[] = $ascending[$i] ? SORT_ASC : SORT_DESC; $args[] = $flag; } - $args[] &= $array; + $args[] = &$array; call_user_func_array('array_multisort', $args); } } \ No newline at end of file diff --git a/tests/unit/framework/util/ArrayHelperTest.php b/tests/unit/framework/util/ArrayHelperTest.php new file mode 100644 index 0000000..a713381 --- /dev/null +++ b/tests/unit/framework/util/ArrayHelperTest.php @@ -0,0 +1,50 @@ + 'b', 'age' => 3), + array('name' => 'a', 'age' => 1), + array('name' => 'c', 'age' => 2), + ); + ArrayHelper::multisort($array, 'name'); + $this->assertEquals(array('name' => 'a', 'age' => 1), $array[0]); + $this->assertEquals(array('name' => 'b', 'age' => 3), $array[1]); + $this->assertEquals(array('name' => 'c', 'age' => 2), $array[2]); + + // multiple keys + $array = array( + array('name' => 'b', 'age' => 3), + array('name' => 'a', 'age' => 2), + array('name' => 'a', 'age' => 1), + ); + ArrayHelper::multisort($array, array('name', 'age')); + $this->assertEquals(array('name' => 'a', 'age' => 1), $array[0]); + $this->assertEquals(array('name' => 'a', 'age' => 2), $array[1]); + $this->assertEquals(array('name' => 'b', 'age' => 3), $array[2]); + + // case-insensitive + $array = array( + array('name' => 'a', 'age' => 3), + array('name' => 'b', 'age' => 2), + array('name' => 'A', 'age' => 1), + ); + ArrayHelper::multisort($array, array('name', 'age'), SORT_ASC, array(SORT_STRING|SORT_FLAG_CASE, SORT_REGULAR)); + $this->assertEquals(array('name' => 'A', 'age' => 1), $array[0]); + $this->assertEquals(array('name' => 'a', 'age' => 3), $array[1]); + $this->assertEquals(array('name' => 'b', 'age' => 2), $array[2]); + } +}