PHP how to sort array with user defined keys

By | September 25, 2019
Spread the love

Many times, we need to do sort array with some user defined keys. So we can use pre defined php function to make it easier.  We can array_flip function to achieve it,

array_flip — Exchanges all keys with their associated values in an array.  array_flip() returns an array in flip order, i.e. keys from array become values and values from array become keys.

Note that the values of array need to be valid keys, i.e. they need to be either integer or string. A warning will be emitted if a value has the wrong type, and the key/value pair in question will not be included in the result.

If a value has several occurrences, the latest key will be used as its value, and all others will be lost.

 

Imagine you had an array like the following:

// original array

$user = array(
  'age' => 45, 
  'email' => '[email protected]', 
  'last_login' => '2016-10-21', 
  'name' => 'John Doe'
);

And you wanted to sort its keys based on a custom sort order supplied in another array, for example:

/ sort order we want
$order = array('name', 'email', 'age', 'last_login');

$ordered_array = array_merge(array_flip($order), $user);

Based on which, you would expect the following result:

output: array(
  'name' => 'John Doe', 
  'email' => '[email protected]', 
  'age' => 45, 
  'last_login' => '2016-10-21'
);