Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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' => '...',
    ),
  )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
435 views
Welcome To Ask or Share your Answers For Others

1 Answer

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));
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...