I want to sort elements in an array '$to_sort' with regards to how these elements are sorted in a different array '$sorting_order'.
However, I don't know how to handle the case when the two arrays contain different elements.
$sorting_order[]=[introduction,skills,education,experience]
$to_sort[]=[experience,skills,education]
This is the desired result:
$sorted[]=[skills,education,experience]
**SOLUTION: i got this solution that is,
$sorted = array_intersect($sorting_order, $to_sort);
print_r($sorted);
**
I would approach it this way:
1) flip a
around using array_flip()
; this will create a map with the string values as the key and an ordinal value as the value.
2) use the map from 1) in usort()
.
$amap = array_flip($a);
usort($b, function($str1, $str2) use ($amap) {
$key1 = $amap[$str1]; // decide what to do if the key doesn't exist
$key2 = $amap[$str2];
if ($key1 > $key2) {
return 1;
} elseif ($key1 == $key2) {
return 0;
} else {
return -1;
}
});