gpt4 book ai didi

php - 在多维数组中查找最小值并返回键

转载 作者:行者123 更新时间:2023-12-01 22:17:03 26 4
gpt4 key购买 nike

我在这里读过几个类似的问题,比如这个,Finding the minimum value's key in an associative array但我认为我的问题可能是独一无二的,因为我的源数组不是作为键的字符串。

我的源数组看起来像这样,

$dealers = array(
array(
[id] => 1526,
[count] => 2
),
array(
[id] => 1518,
[count] => 5
),
array(
[id] => 1511,
[count] => 9
),
array(
[id] => 1410,
[count] => 3
)
);

我需要获取最小的 count 值的 id

我试过以下,

$low_dealer = array_keys($dealers, min($dealers));

但它似乎返回的是最低 id 的索引,而不是计数。

我的下一次尝试是结合我发现的另一个函数来查找特定列的最小值,

$low_dealer = array_keys($dealers, min( array_column( $dealers, 'count' ) ));

但那没有返回任何结果。

编辑:还必须能够处理多个分钟,如果两个或多个具有相同的计数,需要取回它们的数组以便我可以rand() 它。

在此感谢任何提示,谢谢!

最佳答案

// indexed array: 2, 5, 9, 3
$counts = array_column($dealers, 'count');

// find index of min value
$index = array_search(min($counts), $counts, true);

// $dealers[$index]['id'];

关于php - 在多维数组中查找最小值并返回键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44660139/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com