如何检查是否存在多数组密钥?
示例:
$array = array(
array('first_id' => 2, 'second_id' => 4, 'third_id' => 6),
array('first_id' => 3, 'second_id' => 5, 'third_id' => 7)
);
现在我想检查数组中是否存在带params的行:
first_id = 3,
second_id = 5,
third_id = 6.
在这个例子中,我不应该得到任何结果,因为third_id = 6不存在(它存在但是first_id = 2和second_id = 4)。
如何在PHP中轻松查看?
感谢。
答案 0 :(得分:3)
对于具有相同键和值的数组,PHP的本机数组相等性检查将返回true,因此您应该只能使用in_array
- 它将处理&#34 ;深度"自动:
$set = [
['first_id' => 2, 'second_id' => 4, 'third_id' => 6],
['first_id' => 3, 'second_id' => 5, 'third_id' => 7]
];
$tests = [
['first_id' => 3, 'second_id' => 5, 'third_id' => 7],
['first_id' => 3, 'second_id' => 5, 'third_id' => 6],
['first_id' => 2, 'second_id' => 4, 'third_id' => 6],
['first_id' => 2, 'second_id' => 5, 'third_id' => 6],
];
foreach ($tests as $test) {
var_dump(in_array($test, $set));
}
BOOL(真)
布尔(假)
BOOL(真)
布尔(假)
如果数组键的顺序也很重要,请将第三个参数true
添加到in_array
调用中。这将使用严格相等而不是松散,并要求对数组进行相同的排序。请在此处查看有关平等的信息:http://php.net/manual/en/language.operators.array.php
答案 1 :(得分:0)
您可以使用isset
,array_search
和array_filter
只有一个班轮尝试这个..
$array = array(
array('first_id' => 2, 'second_id' => 4, 'third_id' => 6),
array('first_id' => 3, 'second_id' => 5, 'third_id' => 7)
);
$first_id = 2;
$second_id = 4;
$third_id = 6;
//check and get array index if exist
$index = array_keys(array_filter($array, function($item) use ($first_id,
$second_id, $third_id) { return $item['first_id'] === $first_id &&
$item['second_id'] === $second_id && $item['third_id'] === $third_id; }));
//print out that array index
print_r($array[$index[0]]);