I have PHP array that looks like
$my_arr['cats'] = array('Shadow', 'Tiger', 'Luna');
$my_arr['dogs'] = array('Buddy', 'Lucy', 'Bella');
$my_arr['dolphins'] = array('Sunny', 'Comet', 'Pumpkin');
$my_arr['lizzards'] = array('Apollo', 'Eddie', 'Bruce');
//and many more lines like this
I need to sort it based on it keys using sorting array like
$order = array('lizzards', 'cats');
I want that the first item should be lizzards array, second item - cats and then all items that were not specified in $order array. How it can be done using usort / uasort / uksort functions?
You can achieve this by below code
<?php
function sortByKey(&$arr,$key_order)
{
if(count(array_intersect(array_keys($arr),$key_order))!=count($key_order))
{
return false;
}
$ordered_keys=array_merge($key_order,array_diff(array_keys($arr),$key_order));
$sorted_arr=[];
foreach($ordered_keys as $key)
{
$sorted_arr[$key]=$arr[$key];
}
$arr=$sorted_arr;
return true;
}
$my_arr=[];
$my_arr['cats'] = array('Shadow', 'Tiger', 'Luna');
$my_arr['dogs'] = array('Buddy', 'Lucy', 'Bella');
$my_arr['dolphins'] = array('Sunny', 'Comet', 'Pumpkin');
$my_arr['lizzards'] = array('Apollo', 'Eddie', 'Bruce');
$order = array('lizzards', 'cats');
if(sortByKey($my_arr,$order){
echo "Sorting done successfully";
}
else
{
echo "Sorting ignored, order element miss matched";
}
print_r($my_arr);
?>
A shorter solution using uksort:
uksort($my_arr, function ($a,$b) use ($order) {
//Look for elements indexes in the 'order' array
$aKey = array_search($a, $order);
$bKey = array_search($b, $order);
if($aKey !== FALSE && $bKey !== FALSE) {
return $aKey - $bKey;
} else if($aKey !== FALSE) {
return -1;
} else if($bKey !== FALSE) {
return 1;
}
return 0;
});