diff --git a/lib/Cake/Test/Case/Utility/HashTest.php b/lib/Cake/Test/Case/Utility/HashTest.php index d60aa95d0cb..18862d8fa7a 100644 --- a/lib/Cake/Test/Case/Utility/HashTest.php +++ b/lib/Cake/Test/Case/Utility/HashTest.php @@ -1033,6 +1033,43 @@ public function testSortWithOutOfOrderKeys() { $this->assertEquals($expected, $result); } +/** + * test sorting with string keys. + * + * @return void + */ + public function testSortString() { + $to_sort = array( + 'four' => array('number' => 4, 'some' => 'foursome'), + 'six' => array('number' => 6, 'some' => 'sixsome'), + 'five' => array('number' => 5, 'some' => 'fivesome'), + 'two' => array('number' => 2, 'some' => 'twosome'), + 'three' => array('number' => 3, 'some' => 'threesome') + ); + $sorted = Hash::sort($to_sort, '{s}.number', 'asc'); + $expected = array( + 'two' => array('number' => 2, 'some' => 'twosome'), + 'three' => array('number' => 3, 'some' => 'threesome'), + 'four' => array('number' => 4, 'some' => 'foursome'), + 'five' => array('number' => 5, 'some' => 'fivesome'), + 'six' => array('number' => 6, 'some' => 'sixsome') + ); + $this->assertEquals($expected, $sorted); + + $menus = array( + 'blogs' => array('title' => 'Blogs', 'weight' => 3), + 'comments' => array('title' => 'Comments', 'weight' => 2), + 'users' => array('title' => 'Users', 'weight' => 1), + ); + $expected = array( + 'users' => array('title' => 'Users', 'weight' => 1), + 'comments' => array('title' => 'Comments', 'weight' => 2), + 'blogs' => array('title' => 'Blogs', 'weight' => 3), + ); + $result = Hash::sort($menus, '{s}.weight', 'ASC'); + $this->assertEquals($expected, $result); + } + /** * Test insert() * diff --git a/lib/Cake/Utility/Hash.php b/lib/Cake/Utility/Hash.php index 54e951c1ac7..83597078d70 100644 --- a/lib/Cake/Utility/Hash.php +++ b/lib/Cake/Utility/Hash.php @@ -695,7 +695,8 @@ public static function apply(array $data, $path, $function) { */ public static function sort(array $data, $path, $dir) { $originalKeys = array_keys($data); - if (is_numeric(implode('', $originalKeys))) { + $numeric = is_numeric(implode('', $originalKeys)); + if ($numeric) { $data = array_values($data); } $sortValues = self::extract($data, $path); @@ -722,7 +723,15 @@ public static function sort(array $data, $path, $dir) { $keys = array_unique($keys); foreach ($keys as $k) { - $sorted[] = $data[$k]; + if ($numeric) { + $sorted[] = $data[$k]; + continue; + } + if (isset($originalKeys[$k])) { + $sorted[$originalKeys[$k]] = $data[$originalKeys[$k]]; + } else { + $sorted[$k] = $data[$k]; + } } return $sorted; }