The closest answer I saw was This One, but that’s not what I need.
Let’s say I have the following array:
$array = array (
'docker-compose' =>
array (
'download_url' => '...',
),
'darwin' =>
array (
'download_url' => '...',
),
'linux' =>
array (
'download_url' => '....',
),
'windows' =>
array (
'download_url' => '...',
),
'debian' =>
array (
'download_url' => '...',
'install_command' => '....',
),
'rpm' =>
array (
'download_url' => '...',
'install_command' => '...',
),
'helm' =>
array (
'install_command' => '...',
'wiki_url' => '',
),
'docker' =>
array (
'install_command' => '....',
),
)
And I want to sort it according to a simple logic that comes out from the following array:
$artifacts_importance_order = array(
'helm',
'rpm',
'debian',
'docker',
'docker-compose',
'linux',
'windows',
'darwin',
);
If I was able to get the array’s key
inside usort()
I’d do something like that:
usort($array, function($a, $b) use ($artifacts_importance_order){
return (array_search(get_array_key($a),$artifacts_importance_order) < array_search(get_array_key($b),$artifacts_importance_order));
});
Of course, get_array_key
does not exist, but I’d like to know if there’s something else I can do to get the key.
The desired result will be:
$array = array (
'helm' =>
array (
'install_command' => '...',
'wiki_url' => '',
),
'rpm' =>
array (
'download_url' => '...',
'install_command' => '...',
),
'debian' =>
array (
'download_url' => '...',
'install_command' => '....',
),
'docker' =>
array (
'install_command' => '....',
),
'docker-compose' =>
array (
'download_url' => '...',
),
'linux' =>
array (
'download_url' => '....',
),
'windows' =>
array (
'download_url' => '...',
),
'darwin' =>
array (
'download_url' => '...',
),
)
2
Answers
You would need to use
uksort()
instead as this passes the key values to the sort…A more simple approach. You can
array_flip
your order so they become the keys, thenarray_replace
these keys to change the order.See it working over a 3v4l