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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里