0

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' => '...',
    ),
  )
Nadav
  • 1,730
  • 16
  • 20

2 Answers2

2

You would need to use uksort() instead as this passes the key values to the sort...

uksort($array, function($a, $b) use ($artifacts_importance_order){
    return (array_search($a,$artifacts_importance_order) > array_search($b,$artifacts_importance_order));
});
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • Exactly the function I was looking for. Thanks for that. Working as expected. Didn't try Jaquarth's answer, might work just as well. – Nadav Jan 06 '21 at 14:05
1

A more simple approach. You can array_flip your order so they become the keys, then array_replace these keys to change the order.

See it working over a 3v4l

$orderedArray = array_replace(array_flip($artifacts_importance_order), $array);
Jaquarh
  • 6,493
  • 7
  • 34
  • 86