Friday, 13 July 2018

How To Sort An Array By Keys Based On Order In A Secondary Array In PHP?

Imagine you had an array like the following:
// original array
$user = array(
 'age' => 45, 
 'email' => 'john@doe.com', 
 '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');
Based on which, you would expect the following result:
/* output: array(
 'name' => 'John Doe', 
 'email' => 'john@doe.com', 
 'age' => 45, 
 'last_login' => '2016-10-21'
); */
To achieve that, you can use any of the following methods:

Using array_merge()

// PHP 4+
$ordered_array = array_merge(array_flip($order), $user);

Description:

  1. array_flip() changes the $order array's values to keys;
  2. Using array_merge(), since both the arrays have same keys, the values of the first array is overwritten by the second array, whilst the order of keys of the first one is maintained.

Using array_replace()

// PHP 5+
$ordered_array = array_replace(array_flip($order), $user);

Description:

  1. array_flip() changes the $order array's values to keys;
  2. array_replace() replaces the values of the first array with values having the same keys in the second array.

Using uksort()

// PHP 4+
uksort($user, function($key1, $key2) use ($order) {
 return ((array_search($key1, $order) > array_search($key2, $order)) ? 1 : -1);
});

Description:

  1. uksort() allows us to sort an array by keys using a user-defined comparison function that is called multiple times, every time with two keys (in our case, from the $user array);
  2. The result of our custom sort function must return 0 if both items are same, a positive integer if $key1 is greater than $key2 and a negative integer if $key1is less than $key2.

0 comments:

Post a Comment