I have an array that looks like
$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],
//...
];
I would like to sort the array so that the keys country_id, region, region_id, city, city_id occur serially while preserving the position of others.
Expected Output
$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],
//...
];
I have tried as:
Trial #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);
Trial #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);
But the rest of the orders are not maintained anymore.
So I want those custom fields to appear in the same order without breaking the positions of others. For example, name should appear first, etc.
ksort().uksort()will do the job I guessnameto occur early, andzip_codelate? Are you expecting the original order to somehow play a role? I don't see the logic.$orders) should define the anchor for the other matches to assemble around? Why, for instance, are not all matches moved to the slots beforecity_id, so they are adjacent with it, and so thatzip_codewould appear in third place? Your example is quite simple, but it could get even less clear if the matches are spread all over a very large array, completely out of order. Where should the matches assemble?