我希望首先根据另一个数组的顺序来排序值。
$countries = explode(',', 'AF,AL,DZ,AS,AD,FR,AO,AI,AQ,GB');
$popular = explode(',', 'FR,GB');
我来自$countries,我希望将$popular
中定义的值组成以下数组:
$ordered = ['GB,FR,AF,AL,DZ,AS,AD,AO,AI,AQ']
谢谢
您可以使用array_merge和array_diff
查看工作演示::https://eval.in/873974
$countries = explode(',', 'AF,AL,DZ,AS,AD,FR,AO,AI,AQ,GB');
$popular = explode(',', 'FR,GB');
sort($popular); // sort to manage order
// remove common element from $countries and merge with $popular
$ordered = array_merge($popular,array_diff($countries, $popular));
echo "<pre>";
print_r($ordered);
试试这段代码
<?php
$arr= array();
$countries = explode(',', 'AF,AL,DZ,AS,AD,FR,AO,AI,AQ,GB');
$popular = explode(',', 'FR,GB');
$total_popular = count($popular);
$total_countries = count($countries);
for ($i=0; $i < $total_popular; $i++) {
if (in_array($popular[$i], $countries)) {
$arr[]=$popular[$i];
}
}
for ($j=0; $j < $total_countries; $j++) {
if (! in_array($countries[$j], $arr)) {
$arr[]=$countries[$j];
}
}
echo "<pre>";
print_r($arr);
?>
您希望此代码的输出为: