0

I have two arrays and I want to sort first array in ascending order where as I want second array sorted in descending order in PHP. So I used array_multisort() function. The first array is sorted as expected but the second array is not sorted as I wish.

Below is the code.

<?php
        $array1 = array("ninja","pirate","assasin","superhero");
        $array2 = array("elephant","panda","eagle","snake");
        echo "<pre>";
        echo "Array 1.) <br />";
        print_r($array1);
        echo "<hr />Array 2.) <br />";
        print_r($array2);
        array_multisort($array1,SORT_ASC,$array2,SORT_DESC);
        echo "<hr/>New Sorted Array 1.) <br />";
        print_r($array1);
        echo "<hr />";
        echo "New Sorted Array 2.) <br />";
        print_r($array2);
        echo "</pre>";
    ?>

I am a beginner in PHP. Please comment below for any query.

2 Answers 2

1

keep it simple...

array_multisort($array1, SORT_ASC, SORT_STRING);
array_multisort($array2, SORT_DESC, SORT_STRING);
Sign up to request clarification or add additional context in comments.

Comments

1

I don't think you understand how array_multisort works. If you check the first example in the manual, it will rearrenge the second array, based on how the first got sorted.

If you want to sort them independently, use sort and rsort, like this:

sort($array1);
rsort($array2);

2 Comments

I just trusted this [w3schools] link w3schools.com/php/…
@RK Yeah but did you really stop to analyse the output? M->P->F in the second array. Does that seem desc to you? Again, it's based on how the first array got sorted. Check the manual (ex 2) and the examples that involve data that actually relate to each other, such as data you'd have in a table. Edit: And think about it, if you want to sort one column, the rows in the other column should match. Think of two columns in excel, and you want to sort one column, but match the second one...

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.