PHP array_multisort does not sort second array correctly

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 the second array wrong? If this is correct, can anyone explain how this is correct?

Thank.

+3


source to share


5 answers


Yes, that's right. You are using PHP array_multisort function incorrectly. It will not sort both arrays, but it will sort the first array, and the second array will be ordered in the same order as the first array.

$ numbers Before sorting:

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

      

After sorting:



(
  [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 be sorted, but will get its elements according to the 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
)

      

0


source


This is expected behavior array_multisort

. The first array is sorted and the second array is overridden, so its values ​​continue to match the same values ​​in the first array. Note that when the first array has equal values ​​(two 100

s), the values ​​of the second array are sorted internally (therefore Amanda

preceded by Jane

).



If you want to sort the two arrays yourself, you can just use two calls sort

.

0


source


its easy:

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

0


source


PHP array_multisort works for sorting the first array and ordering the second array according to the elements of the first array, as well as sorting both.

0


source


$ 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);

0


source







All Articles