检查关联数组是否包含值,并检索数组中的键/位置 [英] Check if associative array contains value, and retrieve key / position in array
问题描述
我正在努力解释我要在这里做的事情,如果让我感到困惑,请您道歉..我也很困惑自己
I'm struggling to explain what I want to do here so apologies if I confuse you.. I'm just as confused myself
我有一个像这样的数组:
I have an array like so:
$foo = array(
array('value' => 5680, 'text' => 'Red'),
array('value' => 7899, 'text' => 'Green'),
array('value' => 9968, 'text' => 'Blue'),
array('value' => 4038, 'text' => 'Yellow'),
)
我想检查数组是否包含值,例如7899,并在上面的示例中也获得了链接到该值"Green"的文本.
I want to check if the array contains the value e.g. 7899 and also get the text linked to that value "Green" in the example above.
推荐答案
尝试类似的方法
$foo = array(
array('value' => 5680, 'text' => 'Red'),
array('value' => 7899, 'text' => 'Green'),
array('value' => 9968, 'text' => 'Blue'),
array('value' => 4038, 'text' => 'Yellow'),
);
$found = current(array_filter($foo, function($item) {
return isset($item['value']) && 7899 == $item['value'];
}));
print_r($found);
哪个输出
Array
(
[value] => 7899
[text] => Green
)
此处的键是array_filter
.如果搜索值7899
不是静态的,则可以使用诸如function($item) use($searchValue)
之类的东西将其带到闭包中.请注意,array_filter
返回一个元素数组,这就是为什么我将其通过current
The key here is array_filter
. If the search value 7899
is not static then you could bring it in to the closure with something like function($item) use($searchValue)
. Note that array_filter
is returning an array of elements which is why I pass it through current
这篇关于检查关联数组是否包含值,并检索数组中的键/位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!