Custom key to sort flat association based on another array
P粉541551230
P粉541551230 2023-10-15 19:52:40
0
2
657

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粉541551230
P粉541551230

reply all(2)
P粉762730205

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粉277824378

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template