0

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

sulman
  • 2,431
  • 7
  • 40
  • 62
  • How would this be sorted since L is not between N or V in the alphabet ? Are you sure of your wanted output ? – jiboulex Dec 21 '15 at 14:59
  • That is exactly my problem...Yes the output needs to be in this order – sulman Dec 21 '15 at 15:04
  • So it's not a logical order at all, how would you expect any function to guess the order you want ? Don't you have any other way to sort your array, a property in each of your array objects maybe ? – jiboulex Dec 21 '15 at 15:07
  • I don't need it to "guess" the order. I'm giving it the order. (or that's the plan anyway!). – sulman Dec 21 '15 at 15:09
  • You just deal with this 3 keys or maybe there will be more ? Only letters or possibly integers in the keys ? – jiboulex Dec 21 '15 at 15:14

1 Answers1

1

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

Community
  • 1
  • 1
Alaa M. Jaddou
  • 1,180
  • 1
  • 11
  • 30
  • That is exactly what I was trying to achieve! Just needed to change function `sortArray(array $array, array $order)` to `function sortArray(array $array, array $orderArray)` - Thank you :) – sulman Dec 21 '15 at 15:22