phparrayssortingkeyassociative-array

Custom key-sort a flat associative based on another array


Is it possible in PHP to do something like this? How would you go about writing a function? Here is an example. The order is the most important thing.

$customer['address'] = '123 fake st';
$customer['name'] = 'Tim';
$customer['dob'] = '12/08/1986';
$customer['dontSortMe'] = "this value doesn't need to be sorted";

And I'd like to do something like

$properOrderedArray = sortArrayByArray($customer, array('name', 'dob', 'address'));

Because at the end I use a foreach() and they're not in the right order (because I append the values to a string which needs to be in the correct order and I don't know in advance all of the array keys/values).

I've looked through PHP's internal array functions but it seems you can only sort alphabetically or numerically.


Solution

  • Just use array_merge or array_replace. array_merge works by starting with the array you give it (in the proper order) and overwriting/adding the keys with data from your 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 'stale' question, because I think all the loops given as previous answers are overkill.