Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

My first array:

normalArray
(
    [0] => Business Class
    [2] => Economy
    [6] => First Class
)

My sorting array:

sortArray
(
    [0] => Economy
    [1] => Business Class
    [2] => First Class
)

I am trying to get this as my result

resultsArray
(
    [2] => Economy
    [0] => Business Class
    [6] => First Class
)

Note that the key and value needs to follow the correct order. So i would need to sort array by an array while keeping the key to the value.

I have searched around and looked at many different examples.

Thanks

share|improve this question
 
stackoverflow.com/questions/348410/… –  user1646111 Feb 6 '13 at 7:00
1  
@tony what u use for sorting array? –  Tony Stark Feb 6 '13 at 7:04
add comment

5 Answers

up vote 0 down vote accepted

Try this:

$map = array_flip($sortArray);
uasort($normalArray,function($a,$b) use ($map) {return $map[$a] < $map[$b] ? -1 : 1});
share|improve this answer
 
Thanks!!! it works –  tony Feb 6 '13 at 7:35
add comment

Try this asort() or arsort()

Example:

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
--OR--
arsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

The above example will output:

a = orange
d = lemon
b = banana
c = apple

For more sorting function attributes check out this link.

may this help you.

share|improve this answer
add comment

I believe what you are looking for is asort.

share|improve this answer
 
Asort doesnt provide with the same results im looking for, the result order will need to be same as my other array. –  tony Feb 7 '13 at 1:37
add comment

Try this arsort()

Example:

 normalArray
(
    [0] => Economy
    [2] => Business Class
    [6] => First Class
)

The above example will output:

resultsArray
(
    [2] => Business Class
    [0] => Economy
    [6] => First Class
)
share|improve this answer
 
Doing a arsort or asort doesnt provide the result im asking for. The order will need to be same as my sorting array. Not just checking by alphabetical. Thanks resultsArray ( [2] => Economy [0] => Business Class [6] => First Class ) –  tony Feb 7 '13 at 1:35
add comment
asort($normalArray);

this maintains the index of the array.

ref: http://php.net/manual/en/function.sort.php

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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