2022-07-24 02:05:53 -06:00
|
|
|
<?php
|
2023-10-04 21:36:11 +03:30
|
|
|
|
2022-07-24 02:05:53 -06:00
|
|
|
/**
|
|
|
|
* Sort an "Array of objects" or "Array of arrays" by keys
|
|
|
|
*/
|
|
|
|
|
|
|
|
class ArrayKeysSort
|
|
|
|
{
|
|
|
|
public const ORDER_ASC = 'ASC';
|
|
|
|
public const ORDER_DESC = 'DESC';
|
2023-10-04 21:36:11 +03:30
|
|
|
/**
|
2022-07-24 02:05:53 -06:00
|
|
|
* @param $collection
|
|
|
|
* @param array $keys
|
|
|
|
* @param string $order
|
|
|
|
* @param bool $isCaseSensitive
|
|
|
|
* @return mixed
|
|
|
|
*/
|
2023-10-04 21:36:11 +03:30
|
|
|
public static function sort($collection, array $keys, string $order = self::ORDER_ASC, bool $isCaseSensitive = false)
|
|
|
|
{
|
2022-07-24 02:05:53 -06:00
|
|
|
if (!empty($collection) && !empty($keys)) {
|
|
|
|
try {
|
2023-10-04 21:36:11 +03:30
|
|
|
usort($collection, function ($a, $b) use ($keys, $order, $isCaseSensitive) {
|
|
|
|
|
2022-07-24 02:05:53 -06:00
|
|
|
$pos = 0;
|
2023-10-04 21:36:11 +03:30
|
|
|
do {
|
2022-07-24 02:05:53 -06:00
|
|
|
$key = $keys[$pos];
|
2023-10-04 21:36:11 +03:30
|
|
|
if (is_array($a)) {
|
|
|
|
if (!isset($a[$key]) || !isset($b[$key])) {
|
|
|
|
$errorMsg = 'The key "' . $key
|
2022-07-24 02:05:53 -06:00
|
|
|
. '" does not exist in the collection';
|
2023-10-04 21:36:11 +03:30
|
|
|
throw new Exception($errorMsg);
|
2022-07-24 02:05:53 -06:00
|
|
|
}
|
2023-10-04 21:36:11 +03:30
|
|
|
$item1 = !$isCaseSensitive
|
|
|
|
? strtolower($a[$key]) : $a[$key];
|
|
|
|
$item2 = !$isCaseSensitive
|
|
|
|
? strtolower($b[$key]) : $b[$key];
|
2022-07-24 02:05:53 -06:00
|
|
|
} else {
|
2023-10-04 21:36:11 +03:30
|
|
|
if (!isset($a->$key) || !isset($b->$key)) {
|
|
|
|
$errorMsg = 'The key "' . $key
|
|
|
|
. '" does not exist in the collection';
|
|
|
|
throw new Exception($errorMsg);
|
|
|
|
}
|
|
|
|
$item1 = !$isCaseSensitive
|
|
|
|
? strtolower($a->$key) : $a->$key;
|
|
|
|
$item2 = !$isCaseSensitive
|
|
|
|
? strtolower($b->$key) : $b->$key;
|
2022-07-24 02:05:53 -06:00
|
|
|
}
|
2023-10-04 21:36:11 +03:30
|
|
|
} while ($item1 === $item2 && !empty($keys[++$pos]));
|
|
|
|
if ($item1 === $item2) {
|
|
|
|
return 0;
|
|
|
|
} elseif ($order === self::ORDER_ASC) {
|
|
|
|
return ($item1 < $item2) ? -1 : 1;
|
|
|
|
} else {
|
|
|
|
return ($item1 > $item2) ? -1 : 1;
|
2022-07-24 02:05:53 -06:00
|
|
|
}
|
2023-10-04 21:36:11 +03:30
|
|
|
});
|
2022-07-24 02:05:53 -06:00
|
|
|
} catch (Exception $e) {
|
|
|
|
echo $e->getMessage();
|
|
|
|
die();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return $collection;
|
|
|
|
}
|
|
|
|
}
|