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 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)