lithium\util\Set::sort()
Sorts an array by any value, determined by a Set
-compatible path.
Parameters
-
array
$data
-
string
$path
A
Set
-compatible path to the array value. -
string
$dir
Either
'asc'
(the default) or'desc'
.
Returns
arraySource
public static function sort($data, $path, $dir = 'asc') {
$flatten = function($flatten, $results, $key = null) {
$stack = [];
foreach ((array) $results as $k => $r) {
$id = $k;
if ($key !== null) {
$id = $key;
}
if (is_array($r)) {
$stack = array_merge($stack, $flatten($flatten, $r, $id));
} else {
$stack[] = ['id' => $id, 'value' => $r];
}
}
return $stack;
};
$extract = static::extract($data, $path);
$result = $flatten($flatten, $extract);
$keys = static::extract($result, '/id');
$values = static::extract($result, '/value');
$dir = ($dir === 'desc') ? SORT_DESC : SORT_ASC;
array_multisort($values, $dir, $keys, $dir);
$sorted = [];
$keys = array_unique($keys);
foreach ($keys as $k) {
$sorted[] = $data[$k];
}
return $sorted;
}