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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?