dongzhanjuan5141 2015-02-04 22:39
浏览 60
已采纳

当我在数组中找到最大值时,如何找出它所在的顺序?

Basically I need to find the highest value in an array of numbers and then which order that was in. Say the array was (1,2,3,4,5,1,2,3,4) I would need it to return 5, and what order 5 was in. In this case it would be in 5th place out of 9 values.

I've been finding the max via this method:

$value = array(1,2,3,4,5,7,6,1,4,1,3);
$value = max($freq);

In this case I would need the values 7 and 6 (the place in the array) to be logged.

  • 写回答

1条回答 默认 最新

  • dppi5167 2015-02-04 22:51
    关注

    Given

    $freq = array(1,2,3,4,5,7,6,1,4,1,3);
    $value = max($freq);
    

    This

    $position = array_keys(array_values($freq), [$value]);
    

    Results in

    array(5)
    

    This means, the value has been found at the sixths position (you know, we start counting at 0). It's an array because the maximum value might be at several positions and you probably want to know all of them. Otherwise, use array_search($value, array_values($freq)) instead, this will give you the position of the first occurance.

    I used array_values() to normalize the array keys, feel free to leave it out if you need the actual key or your arrays always have incrementing numerical keys starting at 0.


    Reference

    array_keys

    array array_keys ( array $array [, mixed $search_value [, bool $strict = false ]] )
    

    array_keys() returns the keys, numeric and string, from the array.

    If the optional search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.

    array_values

    array array_values ( array $array )
    

    array_values() returns all the values from the array and indexes the array numerically.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 爬取1-112页所有帖子的标题但是12页后要登录后才能 我使用selenium模拟登录 账号密码输入后 会报错 不知道怎么弄了
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点