Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Port most recent changes in Set to Hash.

See [68eeee8] and
[af57502]
  • Loading branch information...
commit 9015d7801754145a094248efcf3ea904739b45db 1 parent e55927c
@markstory markstory authored
Showing with 48 additions and 2 deletions.
  1. +37 −0 lib/Cake/Test/Case/Utility/HashTest.php
  2. +11 −2 lib/Cake/Utility/Hash.php
View
37 lib/Cake/Test/Case/Utility/HashTest.php
@@ -1034,6 +1034,43 @@ public function testSortWithOutOfOrderKeys() {
}
/**
+ * 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()
*
* @return void
View
13 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;
}
Please sign in to comment.
Something went wrong with that request. Please try again.