Custom order for php array based on indexes -
i have php array 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
i need sort based on keys using sorting array like
$order = array('lizzards', 'cats');
i want first item should lizzards array, second item - cats , items not specified in $order array. how can done using usort / uasort / uksort functions?
you can achieve 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 $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); ?>
Comments
Post a Comment