查找具有最大或最小子数组元素值的数组元素 [英] Find array element with greatest or smallest sub-array element value

查看:74
本文介绍了查找具有最大或最小子数组元素值的数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

元素1表示 x 值最大的元素,元素2表示 x 元素最小的元素.

Element 1 of the following array represents the element with the greatest x value, and element 2 represents the element with the smallest x element.

在不使用PHP代码遍历每个数组的情况下,如何确定具有最大和最小的 x 的元素的索引?

Without looping over each array using PHP code, how can the index of the element with the greatest and smallest x be determined?

$array = [
    ['x'=>5,'y'=>3],
    ['x'=>9,'y'=>3],
    ['x'=>3,'y'=>3],
    ['x'=>7,'y'=>3]
];

推荐答案

提取 x 列并进行计算:

$x = array_column($array, 'x');
$min = min($x);
$max = max($x);

或者,正如 JustOnUnderMillions 指出的那样:

Or, as JustOnUnderMillions points out:

list($min, $max) = [min($x=array_column($array, 'x')), max($x)];

要获取包含该值的数组的索引,只需使用 array_search().如果有多个相同的值,它将返回第一个键:

To get the index of the array containing that value, just use array_search(). It will return the first key if there are multiple identical values:

$x = array_column($array, 'x');
$min = array_search(min($x), $x, true);
$max = array_search(max($x), $x, true);

PHP> = 5.5.0是 array_column()所需要的,或使用

PHP >= 5.5.0 needed for array_column() or use the PHP Implementation of array_column()

这篇关于查找具有最大或最小子数组元素值的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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