I have for example two arrays:
One with exceptions:
array('dog', 'cat', 'macbook')
And another with all values:
array('computer', 'mom', 'cat', 'dog')
I would like to get sorted array with following order:
array('dog', 'cat', 'computer', 'mom') // first with exception order and another elements alphabetically
How to do it?
Here is my code
$exceptions = array('dog', 'cat', 'macbook');
$main_arr = array('computer', 'mom', 'cat', 'dog');
$temp = [];
$result_arr = [];
foreach($exceptions as $k => $v){
if(in_array($v, $main_arr)){
$result_arr[] = $v; // adding in result array which matches exceptions with main array
unset($main_arr[array_search($v,$main_arr)]); // unsetting from main array with matches with exception array
}
}
$main_arr = array_values(array_filter($main_arr)); // correcting indexing of main array
$result_arr = array_merge($result_arr, $main_arr);
print_r($result_arr);
You can write your custom code like this, anyway this code will work
0 comments:
Post a Comment