Browse Source

Added ArrayHelper::multisort() test.

tags/2.0.0-beta
Qiang Xue 12 years ago
parent
commit
499f7bfce8
  1. 6
      framework/util/ArrayHelper.php
  2. 50
      tests/unit/framework/util/ArrayHelperTest.php

6
framework/util/ArrayHelper.php

@ -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
} 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);
} }
} }

50
tests/unit/framework/util/ArrayHelperTest.php

@ -0,0 +1,50 @@
<?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]);
}
}
Loading…
Cancel
Save