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

时间:2014-07-15 13:48:15

标签: php arrays associative-array associative

我很难解释我想在这里做什么,所以如果我迷惑你就道歉...... 我自己也很困惑

我有一个像这样的数组:

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

我想检查数组是否包含值,例如7899并且还获得了上面示例中与该值“绿色”相关联的文本。

3 个答案:

答案 0 :(得分:9)

尝试这样的事情

$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

传递它的原因

答案 1 :(得分:4)

对于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!';

答案 2 :(得分:0)

猜测你想要的东西:

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