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' => '[email protected]',
'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.
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.