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

asked Dec 21, 2015 at 14:54
5
  • How would this be sorted since L is not between N or V in the alphabet ? Are you sure of your wanted output ? Commented Dec 21, 2015 at 14:59
  • That is exactly my problem...Yes the output needs to be in this order Commented Dec 21, 2015 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 ? Commented Dec 21, 2015 at 15:07
  • I don't need it to "guess" the order. I'm giving it the order. (or that's the plan anyway!). Commented Dec 21, 2015 at 15:09
  • You just deal with this 3 keys or maybe there will be more ? Only letters or possibly integers in the keys ? Commented Dec 21, 2015 at 15:14

1 Answer 1

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

answered Dec 21, 2015 at 15:13
1
  • 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 :) Commented Dec 21, 2015 at 15:22

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.