Skip to content

Instantly share code, notes, and snippets.

@AlekVolsk
Last active October 11, 2020 11:19
Show Gist options
  • Save AlekVolsk/54094d1a372d4eac874be0bd1b1e6952 to your computer and use it in GitHub Desktop.
Save AlekVolsk/54094d1a372d4eac874be0bd1b1e6952 to your computer and use it in GitHub Desktop.
Мультисортировка массива
<?php
/**
* array_ksort_nested
* en:sorting an array by multiple arbitrary keys
* ru:сортировка массива по нескольким произвольным ключам
*
* @param array $array
* @param array $args key in $array => acs|desc
* @param bool $saveKeys whether or not to keep the original keys
* @return array
*/
function array_ksort_nested($array, $args = ['id' => 'asc'], $saveKeys = false)
{
$func = $saveKeys ? 'uasort' : 'usort';
$func($array, function($a, $b) use ($args) {
$res = 0;
$a = (object) $a;
$b = (object) $b;
foreach($args as $k => $v) {
if (!isset($a -> $k) || !isset($b -> $k)) { continue; }
if ($a -> $k == $b -> $k) { continue; }
$res = ($a -> $k < $b -> $k) ? -1 : 1;
if (strtolower($v) == 'desc') { $res = -$res; }
break;
}
return $res;
});
return $array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment