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
-
How would this be sorted since L is not between N or V in the alphabet ? Are you sure of your wanted output ?jiboulex– jiboulex2015年12月21日 14:59:20 +00:00Commented Dec 21, 2015 at 14:59
-
That is exactly my problem...Yes the output needs to be in this ordersulman– sulman2015年12月21日 15:04:04 +00:00Commented 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 ?jiboulex– jiboulex2015年12月21日 15:07:38 +00:00Commented 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!).sulman– sulman2015年12月21日 15:09:57 +00:00Commented 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 ?jiboulex– jiboulex2015年12月21日 15:14:32 +00:00Commented Dec 21, 2015 at 15:14
1 Answer 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
-
That is exactly what I was trying to achieve! Just needed to change function
sortArray(array $array, array $order)
tofunction sortArray(array $array, array $orderArray)
- Thank you :)sulman– sulman2015年12月21日 15:22:33 +00:00Commented Dec 21, 2015 at 15:22
lang-php