Last active
October 20, 2016 04:14
-
-
Save ethaizone/9d307355dbee3174f49a9d62827151a5 to your computer and use it in GitHub Desktop.
sortByArray - helper function to sort Array with Array.
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 | |
function sortByArray($array, $sortOrder, $options = SORT_REGULAR, $descending = false) | |
{ | |
// Before first! LOL | |
// I just extend sortBy in Laravel collection to can use with normal array | |
// and it will sort data from another array. | |
// Perfect!! | |
// Before first. We will add diff array index to last item of sortOrder | |
// this will protect error and make another value that don't appear in sortOrder | |
// will stay at last of array | |
foreach ($array as $key => $value) { | |
if (!in_array($key, $sortOrder)) { | |
$sortOrder[] = $key; | |
} | |
} | |
$results = []; | |
// First we will loop through the items and get the comparator from a callback | |
// function which we were given. Then, we will sort the returned values and | |
// and grab the corresponding values for the sorted keys from this array. | |
foreach ($array as $key => $value) { | |
$results[$key] = array_search($key, $sortOrder); | |
} | |
$descending ? arsort($results, $options) | |
: asort($results, $options); | |
// Once we have sorted all of the keys in the array, we will loop through them | |
// and grab the corresponding model so we can set the underlying items list | |
// to the sorted version. Then we'll just return the collection instance. | |
foreach (array_keys($results) as $key) { | |
$results[$key] = $array[$key]; | |
} | |
return $results; | |
} | |
// Example | |
$array = [ | |
'dummy' => '777', | |
'id' => 1, | |
'description' => 'NA', | |
'title' => 'My title' | |
]; | |
$sortOrder = [ | |
'id', | |
'title', | |
'description', | |
]; | |
$array = sortByArray($array, $sortOrder); | |
var_dump($array); | |
// Result | |
/* | |
array:4 [▼ | |
"id" => 1 | |
"title" => "My title" | |
"description" => "NA" | |
"dummy" => "777" | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
why that complicated, any difference from
?