Php 检查关联数组是否包含值,并检索数组中的键/位置

Php 检查关联数组是否包含值,并检索数组中的键/位置,php,arrays,associative-array,associative,Php,Arrays,Associative Array,Associative,我正在努力解释我想在这里做什么,如果我把你弄糊涂了,我向你道歉。。我自己也很困惑 我有这样一个数组: $foo = array( array('value' => 5680, 'text' => 'Red'), array('value' => 7899, 'text' => 'Green'), array('value' => 9968, 'text' => 'Blue'), array('value' => 40

我正在努力解释我想在这里做什么,如果我把你弄糊涂了,我向你道歉。。我自己也很困惑

我有这样一个数组:

$foo = array(
    array('value' => 5680, 'text' => 'Red'), 
    array('value' => 7899, 'text' => 'Green'), 
    array('value' => 9968, 'text' => 'Blue'), 
    array('value' => 4038, 'text' => 'Yellow'),
)

我想检查数组是否包含值,例如7899,并在上面的示例中获取链接到该值“绿色”的文本。

尝试类似的方法

$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\u filter
。如果搜索值
7899
不是静态的,那么您可以使用类似
函数($item)use($searchValue)
的方法将其带到闭包中。请注意,
array\u filter
返回一个元素数组,这就是为什么我要将它通过
current

来猜测您想要什么:

function findTextByValueInArray($fooArray, $searchValue){
    foreach ($fooArray as $bar )
    {
        if ($bar['value'] == $searchValue) {
            return $bar['text'];
        }
    }
}

对于PHP>=5.5.0,使用
array\u column
更容易:

echo array_column($foo, 'text', 'value')[7899];
或可重复,无需每次使用
array\u列

$bar = array_column($foo, 'text', 'value');
echo isset($bar[7899]) ? $bar[7899] : 'NOT FOUND!';

foreach()呢。。。7899未链接到“黄色”。你到底要做什么?@rack\u nilesh为那件事道歉。。解决了这个问题。@Phantom我考虑过这个问题,但我已经嵌套在另外两个foreach循环中了,我想知道是否有更好的方法来解决这个问题。旁注:使用动态搜索值
$find=current(数组过滤器($activityArray,函数($item)use($jobID){return isset($item['jobID'])&$jobID=$item['jobID'];});打印(已找到)