I have read several similar questions on here, such as this, Finding the minimum value's key in an associative array but I think my problem may be unique in that my source array is not strings as keys.

我在这里已经阅读了几个类似的问题,例如,在关联数组中查找最小值的键但我认为我的问题可能是唯一的,因为我的源数组不是字符串作为键。

My source array looks like this,

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

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

I need to get the id of the smallest count value.

我需要得到最小计数值的id。

I have tried the following,

我试过以下,

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

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

But it appears to be returning the index of the lowest id and not count.

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

My next attempt was combining another function I found to find the min of the specific column,

我的下一次尝试是结合我找到的另一个函数来找到特定列的min,

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

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

But that returned nothing.

但这没有任何回报。

EDIT: Also must be able to handle multiple mins, if two or more have the same count number, need to get an array of them back so I can rand() it.

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

Would appreciate any tips here, thank you!

非常感谢这里的任何提示,谢谢!

2 个解决方案

#1


1

$dealersMin = min(array_column($dealers, 'count'));

$dealersWithMinCount = array_filter($dealers, function ($dealer) {
    global $dealersMin;
    return ($dealer['count'] == $dealersMin);
});

var_dump($dealersWithMinCount[array_rand($dealersWithMinCount)]['id']);

eval.in demo

Explanation

  1. First we find the lowest value of 'count' in the array and save that to $dealersMin.
  2. 首先,我们在数组中找到'count'的最低值,并将其保存到$ dealerMin。

  3. Then we need to get all rows in the $dealers array that have a count of $dealersMin and save that in $dealersWithMinCount.
  4. 然后我们需要获取$ dealers数组中所有具有$ dealerMin计数的行,并将其保存在$ dealersWithMinCount中。

  5. Then just pick a random element of $dealersWithMinCount with array_rand()
  6. 然后用array_rand()选择$ dealersWithMinCount的随机元素

更多相关文章

  1. php 基本的常用字符串函数
  2. 如何使用变量访问多维数组中的某些元素?
  3. 用PHP计算字符串中元音的简单方法?
  4. 键入提示 - 指定对象数组
  5. 切出多维数组的一部分
  6. 仅获取单元素php数组中的值的最佳方法。
  7. 如何从其他文件调用数组
  8. php如何判断数组["a","b","c"]中是否含有"a"?
  9. 如何从databse中提取数据到2d数组中?

随机推荐

  1. 编译Android内核
  2. android与unity交互
  3. android,ios app icon 应用图标大小/尺寸
  4. 【Android】android:windowSoftInputMode
  5. android 动态壁纸 3 解决 动态壁纸列表界
  6. android 布局特殊的属性介绍
  7. Android中shape属性详解:(设置圆角、设置渐
  8. 使用Bottom Navigation Activity实现Andr
  9. AndroidMenifest.xml中android:sharedUse
  10. Android属性动画源代码解析(超详细)