dongpixi2648 2017-04-27 18:30
浏览 14
已采纳

从包含相同值的数组中获取x最高值

I'm using the following code to retrieve the highest 3 numbers from an array.

$a = array(1,2,5,10,15,20,10,15);
arsort($a, SORT_NUMERIC);
$highest = array_slice($a, 0, 3);

This code correctly gives me the highest three numbers array(20,15,10); however, I'm interested in getting the highest 3 numbers including the ones that are identical. In this example, I'm expecting to get an array like array(10, 10, 15, 15, 20)

  • 写回答

4条回答 默认 最新

  • duanjipiao7076 2017-04-27 18:53
    关注

    Might be simpler but my brain is tired. Use arsort() to get the highest first, count the values to get unique keys with their count and slice the first 3 (make sure to pass true to preserve keys):

    arsort($a, SORT_NUMERIC);
    $counts = array_slice(array_count_values($a), 0, 3, true);
    

    Then loop those 3 and fill an array with the number value the number of times it was counted and merge with the previous result:

    $highest = array();
    
    foreach($counts as $value => $count) {
        $highest = array_merge($highest, array_fill(0, $count, $value));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)