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


Check if associative array contains value, and retrieve key / position in array

我正在努力解释我想在这里做什么,所以如果我混淆了你,我很抱歉。我自己也很困惑

我有一个像这样的数组:

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

我想检查数组是否包含值,例如7899,并在上面的例子中获取链接到该值"Green"的文本

试试这样

$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

传递它的原因。

对于PHP>= 5.5.0,使用array_column更容易:

echo array_column($foo, 'text', 'value')[7899];

或者无需每次使用array_column即可重复:

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

猜一下你想要什么:

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