PHP array_multisort没有正确排序第二个数组

Here is my code:

$numbers = array(10, 100, 100, 0);
$names = array("Alex", "Jane", "Amanda", "Debra");
array_multisort($numbers, $names);

print_r($numbers);
print_r($names);

The above code outputs:

Array
(
  [0] => 0
  [1] => 10
  [2] => 100
  [3] => 100
)

Array
(
  [0] => Debra
  [1] => Alex
  [2] => Amanda
  [3] => Jane
)

Why is the sorting of second array incorrect? If it is correct, could anyone explain how is it correct?

Thanks.

Yes, it is correct. You are taking PHP's 'array_multisort' function in wrong way. It will not sort both arrays, but will sort the first array and the second array will have positioning in order corresponding to first array.

$numbers Before sort:

(
  [0] => 10
  [1] => 100
  [2] => 100
  [3] => 0
)

After sort:

(
  [0] => 0 (position before sorting - 3rd)
  [1] => 10 (position before sorting - 0)
  [2] => 100 (position before sorting - 2 or 1)
  [3] => 100 (position before sorting - 2 or 1)
)

So, the second array will not get sort but will get its elements positioned according to first array.

(
  [0] => Debra --in first array 3rd element has moved to 0th position
  [1] => Alex -- in first array 0th element has moved to 1st position
  [2] => Amanda -- in first array 2nd element has moved to 2nd position
  [3] => Jane -- in first array 1st element has moved to 3rd position
)

This is the expected behavior of array_multisort. The first array is sorted, and the second array is reoraganized so its values continue to correspond to the same values of the first array. Note that where the first array has equal values (the two 100s), the second array's values are sorted internally (so Amanda comes before Jane).

If you want to sort two arrays independently, you could just use two sort calls.

its easy :

array_multisort($names, SORT_ASC, SORT_STRING,
$numbers, SORT_NUMERIC, SORT_ASC);
print_r($names);

PHP's array_multisort works to sort first array and arrange second array according to the items of first array rather sort both.

$numbers = array(10, 100, 100, 0);
$names = array("Alex", "Jane", "Amanda", "Debra");
array_multisort($names, SORT_ASC, SORT_STRING);
array_multisort($numbers);


print_r($names);
print_r($numbers);