How does php array_multisort work?

I have a problem to understand array_multisort

See how it is sorted when two values ​​are the same:

$a1=array("Dog","Dog","Cat"); $a2=array("Pluto","Fido","Missy"); array_multisort($a1,$a2); print_r($a1); print_r($a2); 

Code output above:

  Array ( [0] => Cat [1] => Dog [2] => Dog ) Array ( [0] => Missy [1] => Fido [2] => Pluto ) 

let me know why Missy comes first, if you do ascending, it should be an Array ([0] => Fido, [1] => Missy, [2] => Pluto) for a downward vise

also see this

With sorting options:

 $a1=array("Dog","Dog","Cat"); $a2=array("Pluto","Fido","Missy"); array_multisort($a1,SORT_ASC,$a2,SORT_DESC); print_r($a1); print_r($a2); 

Code output above:

  Array ( [0] => Cat [1] => Dog [2] => Dog ) Array ( [0] => Missy [1] => Pluto [2] => Fido ) 

but Array ([0] => Missy [1] => Pluto [2] => Fido) is not in SORT_DESC - this is some type of mixing.

can someone explain to me how the multisort array works, so that I can understand how it works.

+4
source share
3 answers

Well, you sort arrays similarly to programs like Excel. Each array corresponds to a column.

First, all arrays are sorted by the first given array. If there are identical values, the affected ones will be sorted by the second specified array. If there are equal values ​​again, the third array is used, etc.

Or, in other words: arrays are sorted using all arrays, but start on the right (if you think that it really is sorted on all columns once).

In your specific example (second):

First you want to sort in ascending order, so Cat will be the first. Therefore, the last element of the array will be moved to the first position in both arrays. The other two Dog elements are equal. This makes the function look at the next array. He said to sort this array in descending order, so Pluto first. In this case, this leads to the fact that the elements do not move at all (since their order is already correct).

+9
source

Records in the second array corresponding to identical elements in the first array.

+2
source

If you look at the documentation and the first example, you will notice that this is the expected behavior.

With two arguments, both arrays: the first array is sorted; the second array will have its corresponding values, reordered and sorted if the corresponding values ​​in the first column match. As for your example, think about it as you are executing SQL ORDER BY Animal, Name :

  • Cat in the first place
  • Two dogs have a tie, so Fido comes first because Fido <Pluto
+1
source

Source: https://habr.com/ru/post/1394146/


All Articles