From b71d0b43fc7299a8edbef537df4d2322a9268f65 Mon Sep 17 00:00:00 2001 From: Petr Skoda Date: Sun, 10 Jun 2012 18:04:49 +0200 Subject: [PATCH] MDL-33635 add collatorlib::ksort() support --- lib/tests/textlib_test.php | 19 +++++++++++++++++++ lib/textlib.class.php | 27 +++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/lib/tests/textlib_test.php b/lib/tests/textlib_test.php index 4bf7bf26371..68a1bf2e7b0 100644 --- a/lib/tests/textlib_test.php +++ b/lib/tests/textlib_test.php @@ -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); + } } diff --git a/lib/textlib.class.php b/lib/textlib.class.php index 6b7d7b567f5..14dcb5b1880 100644 --- a/lib/textlib.class.php +++ b/lib/textlib.class.php @@ -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; + } } +