Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
910 views
in Technique[技术] by (71.8m points)

arrays - how php array_multisort work?

i have some problem to understand array_multisort

See how it sorts 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);

The output of the code above will be:

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

let me know why Missy comes first, if you do by ascending it must be Array ( [0] => Fido, [1] => Missy, [2] => Pluto ) for descending vise versa

also see this

With sorting parameters:

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

The output of the code above will be:

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

but Array ( [0] => Missy [1] => Pluto [2] => Fido ) not at SORT_DESC is some type of mixed up.

can some one explain me how the array_multisort is working, so that i can understand how it's working.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well, you're sorting the arrays in a similar way to programs like Excel. Each array corresponds to a column.

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

Or in other words: The arrays are sorted using all arrays, but beginning on the right (if you assume it really sorts by all columns once).

For your particular example (the second one):

At first you want to sort in ascending order, so Cat will be first. Therefore the last array element will be moved to the first position in both arrays. The other two elements, Dog are equal. This causes the function to look at the next array. It's told to sort this array in descending order, so Pluto comes first. In this case this leads to the result that the elements aren't moved at all (as their order is correct already).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.7k users

...