dongwei1855
dongwei1855
2017-07-24 04:26

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

5条回答

  • douyanjing8287 douyanjing8287 4年前

    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
    )
    
    点赞 评论 复制链接分享
  • doutou1922 doutou1922 4年前

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

    点赞 评论 复制链接分享
  • duanniu3385 duanniu3385 4年前

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

    点赞 评论 复制链接分享
  • dqtu14636 dqtu14636 4年前

    its easy :

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

    点赞 评论 复制链接分享
  • dongxieting9623 dongxieting9623 4年前

    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.

    点赞 评论 复制链接分享

相关推荐