Commit 499f7bfc by Qiang Xue

Added ArrayHelper::multisort() test.

parent c72d7dc9
...@@ -243,7 +243,7 @@ class ArrayHelper ...@@ -243,7 +243,7 @@ class ArrayHelper
* @throws \yii\base\BadParamException if the $ascending or $sortFlag parameters do not have * @throws \yii\base\BadParamException if the $ascending or $sortFlag parameters do not have
* correct number of elements as that of $key. * 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); $keys = is_array($key) ? $key : array($key);
if (empty($keys) || empty($array)) { if (empty($keys) || empty($array)) {
...@@ -273,10 +273,10 @@ class ArrayHelper ...@@ -273,10 +273,10 @@ class ArrayHelper
} else { } else {
$args[] = static::getColumn($array, $key); $args[] = static::getColumn($array, $key);
} }
$args[] = $ascending[$i]; $args[] = $ascending[$i] ? SORT_ASC : SORT_DESC;
$args[] = $flag; $args[] = $flag;
} }
$args[] &= $array; $args[] = &$array;
call_user_func_array('array_multisort', $args); call_user_func_array('array_multisort', $args);
} }
} }
\ No newline at end of file
<?php
namespace yiiunit\framework\db;
use yii\util\ArrayHelper;
class ArrayHelperTest extends \yii\test\TestCase
{
public function testMerge()
{
}
public function testMultisort()
{
// single key
$array = array(
array('name' => '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]);
}
}
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