skip to Main Content

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


  1. 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));
    });
    
    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search