Reputation: 1
How do I create a PHP function that will order/sort an array by desired order, based on its key?
The array will contain string or numeric value, for example I have:
array = A,B,C,D,E,F
I would like to change the array based on its key so create
create_array_index(5,2,4,1,3,0)
will show array F,C,E,B,D,A
create_array_index(0,2,4,1,3,5)
will show array A,C,E,B,D,F
I know, I can access the value manually ex : $array[5],$array[2],...
and so on, but it will take a lot of time. Is there any function for this?
Upvotes: 0
Views: 568
Reputation: 8509
There are few ways using some php sort functions (like other guys already sugessted), this is another short way how to do this job.
function sortArrayByKey($keystring, $origarray) {
$res = array();
$keys = explode(',', $keystring);
foreach ($keys as $key) $res[] = $origarray[$key];
return $res;
}
$original_array = array('A', 'B', 'C', 'D', 'E', 'F');
$sort_pattern = '5,2,4,1,3,0';
$new_array = sortArrayByKey($sort_pattern, $original_array);
echo "$sort_pattern => " . join(',', $new_array) . "<br />\n";
$sort_pattern = '0,2,4,1,3,5';
$new_array = sortArrayByKey($sort_pattern, $original_array);
echo "$sort_pattern => " . join(',', $new_array) . "<br />\n";
$sort_pattern = '5,4,3,2,1,0';
$new_array = sortArrayByKey($sort_pattern, $original_array);
echo "$sort_pattern => " . join(',', $new_array) . "<br />\n";
$sort_pattern = '0,5,4,2,1,3';
$new_array = sortArrayByKey($sort_pattern, $original_array);
echo "$sort_pattern => " . join(',', $new_array);
5,2,4,1,3,0 => F,C,E,B,D,A
0,2,4,1,3,5 => A,C,E,B,D,F
5,4,3,2,1,0 => F,E,D,C,B,A
0,5,4,2,1,3 => A,F,E,C,B,D
Cheers ;)
Upvotes: 1
Reputation: 11474
There Are a number of array functions in Php and They are all discussed on PHP Official websites. As for I understand you are looking for ksort (Sort Array By keys) and krsort (Sort Array By Keys In Reverse). Please Check them on the given links. And try it yourself.. Goodluck
You can also create your own custom function to do the required job and use it anytime within your application if you feel ksort and krsort are not flexible or accurate to your requirement.
Upvotes: 0
Reputation: 3310
Check the different sort options available in PHP.
Sort based on array keys - https://www.php.net/ksort
You can also sort based on your own comparison function - https://www.php.net/manual/en/function.uksort.php
Upvotes: 0