1

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

2

5 Answers 5

1

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.

0
0

Try this:

$map = array_flip($sortArray);
uasort($normalArray,function($a,$b) use ($map) {return $map[$a] < $map[$b] ? -1 : 1});
0
0

I believe what you are looking for is asort.

1
  • Asort doesnt provide with the same results im looking for, the result order will need to be same as my other array. Commented Feb 7, 2013 at 1:37
0

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
)
1
  • 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 ) Commented Feb 7, 2013 at 1:35
0
asort($normalArray);

this maintains the index of the array.

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

Your Answer

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.