根据另一个数组的(数字)值对(数字)数组进行排序(不是简单的方法)


Sorting an (numerical) array based on (numerical) values of another (not the trivial way)?

$map的值给出顺序:

$map = [
    'region_id'     =>  3,
    'province_id'   =>  4,
    'province_code' =>  5,
    'city_name'     => 11,
    'city_id'       =>  7,
    'is_lead'       => 13,
];

排序主题:

$row = [
    3  => 1,
    4  => 1,
    5  => '001',
    7  => 1001,
    11 => 'Agliè',
    13 => 0,
];

预期成果:

Array
(
    [3] => 1
    [4] => 1
    [5] => 001
    [11] => Agliè
    [7] => 1001
    [13] => 0
)

[确定] 创建临时数组的简单解决方案

$sorted = [];
foreach ($map as $i) {
    $sorted[$i] = $row[$i];
}

[失败] 使用+运算符

不起作用,因为来自 $row 的值不会覆盖$map中的值:

$sorted = array_flip($map) + $row;
print_r($sorted);
Array
(
    [3] => region_id
    [4] => province_id
    [5] => province_code
    [11] => city_name
    [7] => city_id
    [13] => is_lead
)

[失败] 使用array_merge

不起作用,因为索引是数字的:

$sorted = array_merge(array_flip($map), $row);
print_r($sorted);
Array
(
    [0] => region_id
    [1] => province_id
    [2] => province_code
    [3] => city_name
    [4] => city_id
    [5] => is_lead
    [6] => 1
    [7] => 1
    [8] => 001
    [9] => 1001
    [10] => Agliè
    [11] => 0
)

所以你可以试试这个(简单的方法):

$sorted = [];
foreach ($map as $key => $i) {
    $sorted[$i] = $key;
}
ksort($sorted); //sort array by key

这个怎么样?

$ordered = array();
foreach($map as $key) {
    if(array_key_exists($key,$row)) {
        $ordered[$key] = $row[$key];
        unset($row[$key]);
    }
}
return $ordered + $row;