条件数组的第一个元素 [英] First element of array by condition
问题描述
我正在寻找一种优雅的方法来获取满足给定条件的数组的第一个(也是第一个)元素。
I am looking for an elegant way to get the first (and only the first) element of an array that satisfies a given condition.
简单的示例:
输入:
[
['value' => 100, 'tag' => 'a'],
['value' => 200, 'tag' => 'b'],
['value' => 300, 'tag' => 'a'],
]
条件: $ element [ '值']> 199
预期输出:
['value' => 200, 'tag' => 'b']
我自己想出了几种解决方案:
I came up with several solutions myself:
-
遍历数组,检查条件并在找到时中断
Iterate over the array, check for the condition and break when found
使用array_filter进行操作应用条件并获取过滤后的第一个值:
Use array_filter to apply condition and take first value of filtered:
array_values(
array_filter(
$input,
function($e){
return $e['value'] >= 200;
}
)
)[0];
两者似乎都比较麻烦。有人有更清洁的解决方案吗?我是否缺少内置的php函数?
Both seems a little cumbersome. Does anyone have a cleaner solution? Am i missing a built-in php function?
推荐答案
不需要使用上述所有功能,例如 array_filter
。因为 array_filter
过滤器数组。而且过滤与查找第一个值不同。因此,只需执行以下操作:
There's no need to use all above mentioned functions like array_filter
. Because array_filter
filters array. And filtering is not the same as find first value. So, just do this:
foreach ($array as $key => $value) {
if (meetsCondition($value)) {
$result = $value;
break;
// or: return $value; in in function
}
}
array_filter
将过滤整个数组。因此,如果您需要的值是第一个,并且数组包含100个或更多元素,则 array_filter
仍将检查所有这些元素。那么,您真的需要100次迭代而不是1次迭代吗?答案很明确-否。
array_filter
will filter whole array. So if your required value is first, and array has 100 or more elements, array_filter
will still check all these elements. So, do you really need 100 iterations instead of 1? The asnwer is clear - no.
这篇关于条件数组的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!