Supported Versions: PHP 4, PHP 5, PHP 7, PHP 8
Sort an array with a user-defined comparison function and maintain index association
<?php uasort(array &$array, callable $callback): true
<?php $items = $this->items;
$callback && is_callable($callback)
? uasort($items, $callback)
: asort($items, $callback ?? SORT_REGULAR);
return new static($items);
<?php {
$items = $this->items;
uasort($items, function ($a, $b) use ($comparisons, $options) {
foreach ($comparisons as $comparison) {
$comparison = Arr::wrap($comparison);
$prop = $comparison[0];
$ascending = Arr::get($comparison, 1, true) === true ||
Arr::get($comparison, 1, true) === 'asc';
if (! is_string($prop) && is_callable($prop)) {
$result = $prop($a, $b);
} else {
$values = [data_get($a, $prop), data_get($b, $prop)];
if (! $ascending) {
$values = array_reverse($values);
}
if (($options & SORT_FLAG_CASE) === SORT_FLAG_CASE) {
if (($options & SORT_NATURAL) === SORT_NATURAL) {
$result = strnatcasecmp($values[0], $values[1]);
} else {
$result = strcasecmp($values[0], $values[1]);
}
} else {
$result = match ($options) {
SORT_NUMERIC => intval($values[0]) <=> intval($values[1]),
SORT_STRING => strcmp($values[0], $values[1]),
SORT_NATURAL => strnatcmp($values[0], $values[1]),
SORT_LOCALE_STRING => strcoll($values[0], $values[1]),
default => $values[0] <=> $values[1],
};
}
}
if ($result === 0) {
continue;
}
return $result;
}
});
return new static($items);
}
<?php $arr = $this->all();
uasort($arr, function ($a, $b) use ($sorts) {
foreach ($sorts as $sort) {
$bits = explode(':', $sort);
$sort_by = $bits[0];
$sort_dir = array_get($bits, 1);
[$one, $two] = $this->getSortableValues($sort_by, $a, $b);
$result = Compare::values($one, $two);
if ($result !== 0) {
return ($sort_dir === 'desc') ? $result * -1 : $result;
}
}
return 0;
});
return new static($arr);
}
<?php private function appendVersions($json, array $versions)
{
uasort($versions, 'version_compare');
$versions = array_keys(array_reverse($versions));
$json['versions'] = $versions;
<?php }
}
uasort($this->resultPackageMap, $packageSort);
foreach ($this->resultPackagesByName as $name => $packages) {
uasort($this->resultPackagesByName[$name], $packageSort);
}
<?php uasort($this->resultPackageMap, $packageSort);
foreach ($this->resultPackagesByName as $name => $packages) {
uasort($this->resultPackagesByName[$name], $packageSort);
}
}
<?php if (!is_array($header)) {
$header = explode("\r\n", $header);
}
uasort($header, function ($el) {
return stripos($el, 'content-type') === 0 ? 1 : -1;
});
return $header;
}