我有一个看起来像这样的数组:
$array = array(
array('Field1' => 'red', 'Field2' => 'green', 'Field3' => 'blue'),
array('Field1' => 'pink', 'Field2' => 'pinkish', 'Field3' => 'barbiecolor'),
array('Field1' => 'red', 'Field2' => 'blue', ' Field3' => 'orange')
);
我想通过给定的值来检查:
$searchBy = array('Field1' => 'red', 'Field2' => 'blue');
我想要实现的是返回具有所有关联键的父数组&值对匹配。我已经尝试了in_array()
但它不起作用..
答案 0 :(得分:3)
array_filter
可能会更好:
$matches = array_filter($array,function($a) use ($searchBy) {
foreach($searchBy as $k=>$v) {
if( $a[$k] != $v) return false;
}
return true;
});
答案 1 :(得分:1)
您可以尝试:
$find = array_filter($array, function ($a) use($searchBy) {
return array_intersect_assoc($searchBy, $a) == $searchBy;
});
旧学校版
$find = find($searchBy, $array);
print_r($find);
// Function used
function find($needle, $haystack) {
$r = array();
foreach ( $haystack as $k => $a ) {
array_intersect_assoc($needle, $a) == $needle and $r[$k] = $a;
}
return $r;
}