[英]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'),
)
I want to check if the array contains the value eg 7899 and also get the text linked to that value "Green" in the example above. 我想检查数组是否包含值,例如7899,并在上面的示例中获取链接到该值“Green”的文本。
Try something like this 尝试这样的事情
$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);
Which outputs 哪个输出
Array
(
[value] => 7899
[text] => Green
)
The key here is array_filter
. 这里的关键是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)
. 如果搜索值7899
不是静态的,那么你可以function($item) use($searchValue)
将它带入闭包。 Note that array_filter
is returning an array of elements which is why I pass it through current
请注意, array_filter
返回一个元素数组,这就是我通过current
传递它的原因
For PHP >= 5.5.0 it is easier with array_column
: 对于PHP> = 5.5.0,使用array_column
更容易:
echo array_column($foo, 'text', 'value')[7899];
Or to be repeatable without using array_column
each time: 或者每次不使用array_column
时可重复:
$bar = array_column($foo, 'text', 'value');
echo isset($bar[7899]) ? $bar[7899] : 'NOT FOUND!';
Taking a guess at what you would like here: 在这里猜测你想要的东西:
function findTextByValueInArray($fooArray, $searchValue){
foreach ($fooArray as $bar )
{
if ($bar['value'] == $searchValue) {
return $bar['text'];
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.