我想对数组"$to_sort"中的元素进行排序,以了解这些元素如何在不同的数组"$sorting_order"中排序。
但是,当两个数组包含不同的元素时,我不知道如何处理这种情况。
$sorting_order[]=[introduction,skills,education,experience]
$to_sort[]=[experience,skills,education]
这是所需的结果:
$sorted[]=[skills,education,experience]
**溶液:我得到了这个解决方案,即,
$sorted = array_intersect($sorting_order, $to_sort);
print_r($sorted);
**
我会这样处理:
1)使用array_flip()
翻转a
;这将创建一个映射,其中字符串值作为键,序号值作为值。
2)使用1)中的地图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;
}
});