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

mar*_*rry 7 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'),
)
Run Code Online (Sandbox Code Playgroud)

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

jcb*_*lkr 11

尝试这样的事情

$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);
Run Code Online (Sandbox Code Playgroud)

哪个输出

Array
(
    [value] => 7899
    [text] => Green
)
Run Code Online (Sandbox Code Playgroud)

这里的关键是array_filter.如果搜索值7899不是静态的,那么你可以用类似的东西把它带进闭包function($item) use($searchValue).请注意,array_filter返回一个元素数组,这就是我传递它的原因current

  • 旁注:使用动态搜索值`$found = current(array_filter($activityArray, function($item) use($jobID) { return isset($item['jobid']) && $jobID == $item['jobid ']; })); print_r($找到);` (2认同)