是否有一个本地php函数来查看一个值的数组是否在另一个数组中?
问题描述:
有比strpos()循环更好的方法吗?是否有一个本地php函数来查看一个值的数组是否在另一个数组中?
不是我正在寻找部分匹配而不是in_array()类型的方法。
例如针和干草堆和期望的回报:
$needles[0] = 'naan bread';
$needles[1] = 'cheesestrings';
$needles[2] = 'risotto';
$needles[3] = 'cake';
$haystack[0] = 'bread';
$haystack[1] = 'wine';
$haystack[2] = 'soup';
$haystack[3] = 'cheese';
//desired output - but what's the best method of getting this array?
$matches[0] = 'bread';
$matches[1] = 'cheese';
即:
magic_function($大海捞针,%$针%)!
答
我想你混淆了你的问题$haystack
和$needle
,因为烤饼面包不在草堆,也不是cheesestring。您期望的产量表明您正在寻找干酪 in 干酪串。为此,下面将工作:
function in_array_multi($haystack, $needles)
{
$matches = array();
$haystack = implode('|', $haystack);
foreach($needles as $needle) {
if(strpos($haystack, $needle) !== FALSE) {
$matches[] = $needle;
}
}
return $matches;
}
了给定的草垛和针头这个执行快两倍,正则表达式的解决方案。虽然可能会改变不同数量的参数。
答
答
$data[0] = 'naan bread';
$data[1] = 'cheesestrings';
$data[2] = 'risotto';
$data[3] = 'cake';
$search[0] = 'bread';
$search[1] = 'wine';
$search[2] = 'soup';
$search[3] = 'cheese';
preg_match_all(
'~' . implode('|', $search) . '~',
implode("\x00", $data),
$matches
);
print_r($matches[0]);
// [0] => bread
// [1] => cheese
如果你告诉我们更多关于真正问题你会得到更好的答案。
[array_intersect](http://www.php.net/manual/en/function.array-intersect.php) – hsz 2010-04-21 18:21:31
不,不会比'bread'针对'烤饼bread'。 OP似乎在寻找通配符匹配功能。 – 2010-04-21 18:22:19
这将适用于非完全匹配吗? – Haroldo 2010-04-21 18:23:06