我有一个看起来像的数组
$array = [
//...
'name' => ['value' => 'Raj KB'],
'street' => ['value' => 'Street ABC'],
'city' => ['value' => 'Dubai'],
'country_id' => ['value' => 'UAE'],
'region' => ['value' => 'DXB'],
'region_id' => ['value' => 11],
'zip_code' => ['value' => 12345],
'city_id' => ['value' => 22],
//...
];
我想对数组进行排序,以便键country_id, region, region_id, city,city_id连续出现,同时保留其他键的位置。
预期产出
$array = [
//...
'name' => ['value' => 'Raj KB'],
'street' => ['value' => 'Street ABC'],
'country_id' => ['value' => 'UAE'],
'region' => ['value' => 'DXB'],
'region_id' => ['value' => 11],
'city' => ['value' => 'Dubai'],
'city_id' => ['value' => 22],
'zip_code' => ['value' => 12345],
//...
];
我试过:
试验 #1
uksort($array, function ($a, $b) {
$order = ['country_id' => 0, 'region' => 1, 'region_id' => 2, 'city' => 3, 'city_id' => 4];
if (isset($order[$a]) && isset($order[$b])) {
return $order[$a] - $order[$b];
} else {
return 0;
}
});
var_dump($array);
试验 #2
uksort($array, function ($a, $b) {
$order = ['country_id' => 0, 'region' => 1, 'region_id' => 2, 'city' => 3, 'city_id' => 4];
if (!isset($order[$a]) && !isset($order[$b])) {
return 0;
} elseif (!isset($order[$a])) {
return 1;
} elseif (!isset($order[$b])) {
return -1;
} else {
return $order[$a] - $order[$b];
}
});
var_dump($array);
但其余订单不再维护。所以我希望这些自定义字段以相同的顺序出现,而不会破坏其他字段的位置。例如,name应该先出现等等。
海绵宝宝撒
烙印99
阿波罗的战车