【问题标题】:Get value of another key of corresponding highest value in PHP获取PHP中对应最高值的另一个键的值
【发布时间】:2022-07-21 21:08:28
【问题描述】:

我想在数组中的“金额”中获取最高值的“名称”。 代码如下:

$data = [
    ['id' => 0, 'name' => 'Test', 'amount' => 3,],
    ['id' => 1, 'name' => 'Test', 'amount' => 2,],
    ['id' => 2, 'name' => 'Test', 'amount' => 1,],
    ['id' => 3, 'name' => 'Test', 'amount' => 0,],
    ['id' => 4, 'name' => 'High', 'amount' => 6,],
    ['id' => 5, 'name' => 'Test', 'amount' => 4,],
    ['id' => 6, 'name' => 'Test', 'amount' => 5,],
];

【问题讨论】:

  • 你研究和尝试了什么?你被困在哪里了?

标签: php


【解决方案1】:

您可以迭代并比较哪个更大并保持最大。

$max = 0;
$largest = [];
foreach($data as $item) {
    if($item['amount'] > $max) {
        $max = $item['amount'];
        $largest = $item;
    }
}

echo $largest['name'];

打印

High

当然你可以直接使用name,但我认为你想跟踪数量最多的数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多