如果您不关心出现最大值的顶级索引(在本例中为 0、1 或 2)并且您想要搜索整个数组,你可以使用array_search和array_column的这种组合:
$array = [
['key' => 'foo'],
['key' => 'bar'],
['key' => 'baz'],
];
$var = 'hello world';
if (array_search($var, array_column($array, 'key')) === false) {
echo 'var does not exist';
}
这个方法是described in the PHP documentation here。请注意,正如我上面所说,如果您关心它,这不会可靠地为您提供索引。如果您想知道匹配是否存在,我只会使用它。
如果您想要索引,或者您特别不想搜索索引 2(或任何其他任意索引)之外的内容,您可以创建如下函数:
$array = [
['key' => 'foo'],
['key' => 'bar'],
['key' => 'baz'],
];
$var = 'hello world';
function keyValueExists($array, $key, $value, $maxIndex = null) {
foreach ($array as $index => $item) {
if (isset($item[$key]) && $item[$key] === $value) {
return true;
}
if ($maxIndex !== null && $index == $maxIndex) {
break;
}
}
return false;
}
if (keyValueExists($array, 'key', $var, 2) === false) {
echo 'var does not exist';
}