基于另一个(非平凡的方式)的(数值)值对(数值)数组进行排序?

时间:2014-11-17 21:35:43

标签: php arrays

$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
)

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

$sorted = [];
foreach ($map as $i) {
    $sorted[$i] = $row[$i];
}
使用+运算符

[fail]

不起作用,因为来自$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
)

[fail]使用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
)

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

这个怎么样?

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