dongwei1855 2017-07-24 04:26
浏览 215
已采纳

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 2017-07-24 04:37
    关注

    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
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要