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条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化