Is it possible to do something like this in PHP? How would you write a function? Here is an example. Order is most important.
$customer['address'] = '123 fake st'; $customer['name'] = 'Tim'; $customer['dob'] = '12/08/1986'; $customer['dontSortMe'] = 'this value doesnt need to be sorted';
I want to do something similar
$properOrderedArray = sortArrayByArray($customer, array('name', 'dob', 'address'));
Because in the end I used foreach() and they were not in the correct order (because I was appending the values to a string that needed to be in the correct order, and I didn't know all the array keys/values beforehand).
I looked at PHP's internal array functions, but it seems they can only sort alphabetically or numerically.
P粉7627302052023-10-16 17:12:15
for you:
function sortArrayByArray(array $array, array $orderArray) { $ordered = array(); foreach ($orderArray as $key) { if (array_key_exists($key, $array)) { $ordered[$key] = $array[$key]; unset($array[$key]); } } return $ordered + $array; }
P粉2778243782023-10-16 00:38:57
Just use array_merge
or array_replace
. array_merge
works by starting with the array you provide (in the correct order) and then overwriting/adding the keys with the data from the actual array:
$customer['address'] = '123 fake st'; $customer['name'] = 'Tim'; $customer['dob'] = '12/08/1986'; $customer['dontSortMe'] = 'this value doesnt need to be sorted'; $properOrderedArray = array_merge(array_flip(array('name', 'dob', 'address')), $customer); // or $properOrderedArray = array_replace(array_flip(array('name', 'dob', 'address')), $customer); // $properOrderedArray: array( // 'name' => 'Tim', // 'dob' => '12/08/1986', // 'address' => '123 fake st', // 'dontSortMe' => 'this value doesnt need to be sorted')
PS: I'm answering this "outdated" question because I think all the loops given by the previous answers are too much.