Home >Backend Development >PHP Tutorial >How Can I Custom Sort PHP Array Keys Using an External Array?
Custom Key Sorting in PHP Based on External Array
In PHP, it's possible to sort the keys of an associative array based on the order specified in another array. This can be achieved by utilizing the array_merge function:
$customer = [ 'address' => '123 fake st', 'name' => 'Tim', 'dob' => '12/08/1986', 'dontSortMe' => 'this value doesn\'t need to be sorted' ]; $sortOrder = ['name', 'dob', 'address']; $properOrderedArray = array_merge(array_flip($sortOrder), $customer);
The array_merge function combines two arrays, starting with the array specified as the first argument (in this case, the custom order) and overwriting or adding keys from the second array (the customer data) into the merged array.
Output:
[ 'name' => 'Tim', 'dob' => '12/08/1986', 'address' => '123 fake st', 'dontSortMe' => 'this value doesn\'t need to be sorted' ]
It's important to note that this method preserves the original data in the $customer array while creating a new $properOrderedArray with the specified order.
The above is the detailed content of How Can I Custom Sort PHP Array Keys Using an External Array?. For more information, please follow other related articles on the PHP Chinese website!