如何查找数组中的最小数字并返回该数组的主索引? [英] How to find lowest number in an array and return that array's primary index?

查看:128
本文介绍了如何查找数组中的最小数字并返回该数组的主索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像下面的数组。我想在 diff索引中找到编号最小的数组。因此,在这种情况下,我想返回数组[7]。我需要的只是数组编号(即7),而不是其他任何信息。

I have an array that looks like the following. I'd like to find the array with the lowest number in the "diff" index. So in this case, I would want to get back array [7]. All I need is the array number (i.e. 7) not any other info.

我知道我可以使用array_column轻松找到最低的数字,但是如何还返回整体数组索引7?

I know I can use array_column to easily find the lowest number, but how do I also return the overall array index of 7?

[1] => Array
        (
            [qb] => 7
            [rb] => 58
            [wr] => 91
            [te] => 3
            [def] => 11
            [diff] => 136
        )

    [2] => Array
        (
            [qb] => 21
            [rb] => 96
            [wr] => 102
            [te] => 48
            [def] => 15
            [diff] => 240
        )

    [3] => Array
        (
            [qb] => 23
            [rb] => 86
            [wr] => 216
            [te] => 6
            [def] => 32
            [diff] => 287
        )

    [4] => Array
        (
            [qb] => 30
            [rb] => 51
            [wr] => 200
            [te] => 14
            [def] => 17
            [diff] => 266
        )

    [5] => Array
        (
            [qb] => 17
            [rb] => 118
            [wr] => 273
            [te] => 14
            [def] => 30
            [diff] => 380
        )

    [6] => Array
        (
            [qb] => 10
            [rb] => 112
            [wr] => 142
            [te] => 16
            [def] => 4
            [diff] => 264
        )

    [7] => Array
        (
            [qb] => 2
            [rb] => 50
            [wr] => 135
            [te] => 9
            [def] => 20
            [diff] => 104
        )

    [8] => Array
        (
            [qb] => 16
            [rb] => 68
            [wr] => 141
            [te] => 12
            [def] => 1
            [diff] => 224
        )


推荐答案

如您所说,您可以使用array_column和min()。

然后使用array_search查找最小值所在的位置。

As you said you can use array_column and min().
Then use array_search to find the position the min value is in.

//Since the array starts with key 1 then use array_values to reset the array first.
$array = array_values($array);
$diff = array_column($array, "diff");
$min = min($diff);
$key = array_search($min, $diff);

$result = $array[$key];

工作示例:

https://3v4l.org/ci70K

这篇关于如何查找数组中的最小数字并返回该数组的主索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆