Last active
November 29, 2016 23:19
-
-
Save vertexvaar/d9352b347dc0ab2c3c153af7fa4f306e to your computer and use it in GitHub Desktop.
Array sorting functions written a long time ago, don't know why... Maybe to find the ugliest possible way.
This file contains 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 = [ | |
9843 => [ | |
'name' => 'Bob', | |
'order' => '2', | |
], | |
98723 => [ | |
'name' => 'Creg', | |
'order' => '1', | |
], | |
87934 => [ | |
'name' => 'Bobby', | |
'order' => '2', | |
], | |
365 => [ | |
'name' => 'Carl', | |
'order' => '1', | |
], | |
]; | |
$orderBy = [ | |
'order' => SORT_ASC, | |
'name' => SORT_DESC, | |
]; | |
function sortArrayBy(&$array, $orderBy) | |
{ | |
call_user_func_array( | |
'array_multisort', | |
($result = call_user_func( | |
function ($array, $orderBy) { | |
$result = []; | |
for ($i = 0, $j = count($values = array_map(function ($index) use ($array, $orderBy, $i, &$params) { | |
$params[$i . '-' . $index . 'Order'] = $orderBy[$index]; | |
return array_map(function ($item) use ($index) { | |
return $item[$index]; | |
}, array_values($array)); | |
}, array_combine(($keys = array_keys($orderBy)), $keys))) * 2; $i < $j; $i++) { | |
array_push($result, array_values(($i % 2) ? $params : $values)[(int)($i / 2)]); | |
} | |
return $result; | |
}, | |
$array, | |
$orderBy | |
)) + [count($result) + 1 => &$array] | |
); | |
} | |
function sortArrayFe(&$array, $orderBy) | |
{ | |
$params = []; | |
foreach (array_keys($orderBy) as $key) { | |
foreach ($array as $item) { | |
$params[$key][] = $item[$key]; | |
} | |
$params[] = $orderBy[$key]; | |
} | |
$params[] = &$array; | |
call_user_func_array('array_multisort', $params); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment