简体   繁体   English

PHP查找最高键值的索引

[英]PHP Find the Index of the highest key value

I have an array of arrays. 我有一个数组数组。 I would like to find the index of the array of the highest key value Rating. 我想找到最高键值Rating的数组的索引。 For example in the below the array index would be 1. 例如,在下面的数组索引将为1。

Any help would be much appreciated. 任何帮助将非常感激。

 array:3 [
      0 => array:3 [
        "name" => "Nola - Roman Road"
        "rating" => 4.2
        "price_level" => 3
      ]
      1 => array:3 [
        "name" => "The Camel"
        "rating" => 4.6
        "price_level" => 2
      ]
      2 => array:3 [
        "name" => "The Dundee Arms"
        "rating" => 4
        "price_level" => 2
      ]

You can use a few of the array_... functions. 您可以使用一些array_...函数。 First array_column() to extract the column used for the maximum values, then array_keys() to return all of the keys that match the maximum value (found using max($prices) )... 首先array_column()提取用于最大值的列,然后array_keys()返回所有与最大值匹配的键(使用max($prices) )...

$data = [
    0 => [
        "name" => "Nola - Roman Road",
        "rating" => 4.2,
        "price_level" => 3
    ],
    1 => [
        "name" => "The Camel",
        "rating" => 4.6,
        "price_level" => 4
    ],
    2 => [
        "name" => "The Dundee Arms",
        "rating" => 4,
        "price_level" => 2
    ]];

$rating = array_column($data, "rating");
$index = array_keys($rating, max($rating));

print_r($index);

This prints out ... 打印出来...

Array
(
    [0] => 1
)

This will also work if several entries match the maximum value which may help. 如果多个条目匹配最大值,这也可能会起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM