sulman
sulman

Reputation: 2461

PHP - Sort associative array based on predifined order of keys

I have the following structure:

Array
(
    [Lhgee] => some object
    [V4ooa] => some object
    [N0la] => some object
)

I need to sort this array in to this order: V4ooa, Lhgee, N0la so after sorting the array would like this:

Array
(
    [V4ooa] => some object
    [Lhgee] => some object
    [N0la] => some object
)

I've looked at uasort and I'm pretty sure it's what I need (as I need to keep all the data against the relevant array) but can't work out how to acheive this with associative arrays as all the examples seem to use integer indexes. Thanks

Upvotes: 0

Views: 48

Answers (1)

Alaa M. Jaddou
Alaa M. Jaddou

Reputation: 1189

i think you need to check this

$order = array('V4ooa', 'Lhgee', 'N0la');
$array = array
    (
        ['Lhgee'] => some object
        ['V4ooa'] => some object
        ['N0la'] => some object
    );

$orderedArray = sortArray($array, $order);

var_dump($orderedArray);

function sortArray(array $array, array $order) {
    $ordered = array();
    foreach($order as $key) {
        if(array_key_exists($key,$array)) {
            $ordered[$key] = $array[$key];
            unset($array[$key]);
        }
    }
    return $ordered;
}

UPDATE

Check this and This

Upvotes: 1

Related Questions