PHP查找最高键值的索引

时间:2018-10-27 17:21:23

标签: php

我有一个数组数组。我想找到最高键值Rating的数组的索引。例如,下面的数组索引为1。

任何帮助将不胜感激。

 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
      ]

1 个答案:

答案 0 :(得分:0)

您可以使用一些array_...函数。首先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);

这会打印出来...

Array
(
    [0] => 1
)

如果多个条目与最大值匹配可能会起作用。