$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
)
答案 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;