Last active
October 11, 2020 11:19
-
-
Save AlekVolsk/54094d1a372d4eac874be0bd1b1e6952 to your computer and use it in GitHub Desktop.
Мультисортировка массива
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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