我想首先根据基于另一个数组的顺序对值进行排序。
$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']
由于
答案 0 :(得分:2)
您可以使用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);
答案 1 :(得分:0)
试试这段代码
<?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);
?>
此代码的所需输出为