MDL-33635 add collatorlib::ksort() support
This commit is contained in:
@@ -547,6 +547,25 @@ class collatorlib_testcase extends basic_testcase {
|
||||
}
|
||||
return $return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the static ksort method
|
||||
* @return void
|
||||
*/
|
||||
public function test_ksort() {
|
||||
$arr = array('b' => 'ab', 1 => 'aa', 0 => 'cc');
|
||||
$result = collatorlib::ksort($arr);
|
||||
$this->assertSame(array_keys($arr), array(0, 1, 'b'));
|
||||
$this->assertSame(array_values($arr), array('cc', 'aa', 'ab'));
|
||||
$this->assertTrue($result);
|
||||
|
||||
$obj = new stdClass();
|
||||
$arr = array('1.1.1'=>array(), '1.2'=>$obj, '1.20.2'=>null);
|
||||
$result = collatorlib::ksort($arr, collatorlib::SORT_NATURAL);
|
||||
$this->assertSame(array_keys($arr), array('1.1.1', '1.2', '1.20.2'));
|
||||
$this->assertSame(array_values($arr), array(array(), $obj, null));
|
||||
$this->assertTrue($result);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -856,4 +856,31 @@ class collatorlib {
|
||||
self::restore_array($objects, $original);
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Locale aware sorting, the key associations are kept, keys are sorted alphabetically.
|
||||
*
|
||||
* @param array $arr array to be sorted (reference)
|
||||
* @param int $sortflag One of collatorlib::SORT_NUMERIC, collatorlib::SORT_STRING, collatorlib::SORT_NATURAL, collatorlib::SORT_REGULAR
|
||||
* optionally "|" collatorlib::CASE_SENSITIVE
|
||||
* @return bool True on success
|
||||
*/
|
||||
public static function ksort(array &$arr, $sortflag = collatorlib::SORT_STRING) {
|
||||
$keys = array_keys($arr);
|
||||
if (!self::asort($keys, $sortflag)) {
|
||||
return false;
|
||||
}
|
||||
// This is a bit slow, but we need to keep the references
|
||||
$original = $arr;
|
||||
$count = count($arr);
|
||||
for($i=0; $i<$count; $i++) {
|
||||
array_pop($arr);
|
||||
}
|
||||
foreach ($keys as $key) {
|
||||
$arr[$key] = $original[$key];
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user