up vote 5 down vote favorite

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 doesnt 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. Would I have to implement some sort of sorting function with array_walk?

Thank you in advance!

link|flag

3 Answers

up vote 9 down vote accepted

There you go:

function sortArrayByArray($array,$orderArray) {
    $ordered = array();
    foreach($orderArray as $key) {
    	if(array_key_exists($key,$array)) {
    		$ordered[$key] = $array[$key];
    		unset($array[$key]);
    	}
    }
    return $ordered + $array;
}
link|flag
Thank you very much! – alex Dec 8 '08 at 0:38
You're very welcome :) – Eran Galperin Dec 8 '08 at 0:44
So you can join 2 arrays with a + sign? I never knew that, I've been using array_merge()! – alex Sep 24 '09 at 23:08
Is this better than using usort() or uasort()? – grantwparks Sep 25 '09 at 19:57
Excellent function, Thanks Eran. – Neil Aitken Aug 5 at 9:49
up vote 6 down vote
function sortArrayByArray(array $toSort, array $sortByValuesAsKeys)
{
    $commonKeysInOrder = array_intersect_key(array_flip($sortByValuesAsKeys), $toSort);
    $commonKeysWithValue = array_intersect_key($toSort, $commonKeysInOrder);
    $sorted = array_merge($commonKeysInOrder, $commonKeysWithValue);
    return $sorted;
}
link|flag
I didn't know you could cast function arguments like that in PHP! – alex Dec 8 '08 at 5:34
Arrays and classes only. – OIS Dec 8 '08 at 7:33
up vote 0 down vote

IF you have array in your array, you'll have to adapt the function by Eran a little bit...

function sortArrayByArray($array,$orderArray) {
    $ordered = array();
    foreach($orderArray as $key => $value) {
        if(array_key_exists($key,$array)) {
                $ordered[$key] = $array[$key];
                unset($array[$key]);
        }
    }
    return $ordered + $array;
}
link|flag

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.