|
15 | 15 | class Arr |
16 | 16 | { |
17 | 17 | /** |
18 | | - * Subval sort |
| 18 | + * Sorts a multi-dimensional array by a certain column |
19 | 19 | * |
20 | | - * $new_array = Arr::subvalSort($old_array, 'sort'); |
| 20 | + * $new_array = Arr::sort($old_array, 'title'); |
21 | 21 | * |
22 | | - * @param array $array Array |
23 | | - * @param string $subkey Key |
24 | | - * @param string $order Order type DESC or ASC |
| 22 | + * @param array $array The source array |
| 23 | + * @param string $field The name of the column |
| 24 | + * @param string $direction Order type DESC (descending) or ASC (ascending) |
| 25 | + * @param const $method A PHP sort method flag or 'natural' for natural sorting, which is not supported in PHP by sort flags |
25 | 26 | * @return array |
26 | 27 | */ |
27 | | - public static function subvalSort(array $array, string $subkey, string $order = 'ASC') : array |
| 28 | + public static function sort(array $array, string $field, string $direction = 'ASC', $method = SORT_REGULAR) : array |
28 | 29 | { |
29 | | - if (count($array) != 0 || (!empty($array))) { |
30 | | - foreach ($array as $k => $v) { |
31 | | - $b[$k] = function_exists('mb_strtolower') ? mb_strtolower($v[$subkey]) : strtolower($v[$subkey]); |
| 30 | + if (count($array) > 0) { |
| 31 | + |
| 32 | + // Create the helper array |
| 33 | + foreach ($array as $key => $row) { |
| 34 | + $helper[$key] = function_exists('mb_strtolower') ? mb_strtolower($row[$field]) : strtolower($row[$field]); |
32 | 35 | } |
33 | | - if ($order == null || $order == 'ASC') { |
34 | | - asort($b); |
35 | | - } elseif ($order == 'DESC') { |
36 | | - arsort($b); |
| 36 | + |
| 37 | + // Sort |
| 38 | + if($method === SORT_NATURAL) { |
| 39 | + natsort($helper); |
| 40 | + ($direction === 'DESC') and $helper = array_reverse($helper); |
| 41 | + } elseif ($direction == 'DESC') { |
| 42 | + arsort($helper, $method); |
| 43 | + } else { |
| 44 | + asort($helper, $method); |
37 | 45 | } |
38 | | - foreach ($b as $key => $val) { |
39 | | - $c[] = $array[$key]; |
| 46 | + |
| 47 | + // Rebuild the original array |
| 48 | + foreach ($helper as $key => $val) { |
| 49 | + $result[$key] = $array[$key]; |
40 | 50 | } |
41 | | - return $c; |
| 51 | + |
| 52 | + // Return result array |
| 53 | + return $result; |
42 | 54 | } |
43 | 55 | } |
44 | 56 |
|
|
0 commit comments