首先根据另一个数组对数组中的值进行排序

时间:2017-10-05 06:44:29

标签: php arrays sorting foreach

我想首先根据基于另一个数组的顺序对值进行排序。

$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']

由于

2 个答案:

答案 0 :(得分:2)

您可以使用array_mergearray_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);

        ?>

此代码的所需输出为

enter image description here