3 namespace Drupal\Component\Utility;
6 * Provides generic array sorting helper methods.
13 * Sorts a structured array by the 'weight' element.
15 * Note that the sorting is by the 'weight' array element, not by the render
16 * element property '#weight'.
18 * Callback for uasort().
21 * First item for comparison. The compared items should be associative
22 * arrays that optionally include a 'weight' element. For items without a
23 * 'weight' element, a default value of 0 will be used.
25 * Second item for comparison.
28 * The comparison result for uasort().
30 public static function sortByWeightElement(array $a, array $b) {
31 return static::sortByKeyInt($a, $b, 'weight');
35 * Sorts a structured array by '#weight' property.
37 * Callback for uasort().
40 * First item for comparison. The compared items should be associative
41 * arrays that optionally include a '#weight' key.
43 * Second item for comparison.
46 * The comparison result for uasort().
48 public static function sortByWeightProperty($a, $b) {
49 return static::sortByKeyInt($a, $b, '#weight');
53 * Sorts a structured array by 'title' key (no # prefix).
55 * Callback for uasort().
58 * First item for comparison. The compared items should be associative arrays
59 * that optionally include a 'title' key.
61 * Second item for comparison.
64 * The comparison result for uasort().
66 public static function sortByTitleElement($a, $b) {
67 return static::sortByKeyString($a, $b, 'title');
71 * Sorts a structured array by '#title' property.
73 * Callback for uasort().
76 * First item for comparison. The compared items should be associative arrays
77 * that optionally include a '#title' key.
79 * Second item for comparison.
82 * The comparison result for uasort().
84 public static function sortByTitleProperty($a, $b) {
85 return static::sortByKeyString($a, $b, '#title');
89 * Sorts a string array item by an arbitrary key.
92 * First item for comparison.
94 * Second item for comparison.
96 * The key to use in the comparison.
99 * The comparison result for uasort().
101 public static function sortByKeyString($a, $b, $key) {
102 $a_title = (is_array($a) && isset($a[$key])) ? $a[$key] : '';
103 $b_title = (is_array($b) && isset($b[$key])) ? $b[$key] : '';
105 return strnatcasecmp($a_title, $b_title);
109 * Sorts an integer array item by an arbitrary key.
112 * First item for comparison.
114 * Second item for comparison.
116 * The key to use in the comparison.
119 * The comparison result for uasort().
121 public static function sortByKeyInt($a, $b, $key) {
122 $a_weight = (is_array($a) && isset($a[$key])) ? $a[$key] : 0;
123 $b_weight = (is_array($b) && isset($b[$key])) ? $b[$key] : 0;
125 if ($a_weight == $b_weight) {
129 return ($a_weight < $b_weight) ? -1 : 1;