Imagine you had an array like the following:
// original array
$user = [
'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 = ['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:
array_flip()changes the$orderarray's values to keys;- 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:
array_flip()changes the$orderarray's values to keys;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:
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$userarray);- The result of our custom sort function must return
0if both items are same, a positive integer if$key1is greater than$key2and a negative integer if$key1is less than$key2.