dsaeyrq451928 2017-03-31 03:21
浏览 60
已采纳

按整数值排序PHP数组,同时保持Key [duplicate]

This question already has an answer here:

I have an array like this

[Title 1] => 2
[Title 2] => 4
[Title 3] => 3
[Title 4] => 1

All I'm trying to do is sort the integer value in the array, to get an output like this:

[Title 2] => 4
[Title 3] => 3
[Title 1] => 2
[Title 4] => 1

I don't think it matters, but my array is created by the array_count_values function.

$array = array_count_values($originalarray);

I've looked through the manual on PHP: Array Sorting but can't get anything to work.

I've tried a few things that look like they might work.

$newarray = arsort($array);

This just outputs 1

same with rsort.

The closest I've come is by using array_multisort by using it as such:

$array = array_count_values($originalarray);
$newarray = array_multisort($array, SORT_NUMERIC, SORT_DESC);

Now if I do a print_r($array) it outputs like this:

[Title 2] => 4
[1] => 3
[Title 1] => 2
[2] => 1

Meaning it's, for some reason, and seemingly randomly, destroying the key value in the array and putting in place 1, 2, etc in place of Title #

This seems like it would be so easy, yet I've been trying multiple things without luck. Can anyone shine some light on this for me?

</div>
  • 写回答

1条回答 默认 最新

  • ds42774 2017-03-31 03:24
    关注

    sort functions in php return boolean not an array - http://php.net/manual/en/function.arsort.php Sort function will update the array you put as parameter Should be like this

    <?php
    $array = [];
    arsort($array);
    var_dump($array);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题