PHP array_search

时间:2011-04-12 06:35:25

标签: php arrays

是否有任何函数可以使用$ needle作为数组来完成array_search的等效操作?比如,这将是一个理想的解决方案:

$needle = array('first', 'second');
$haystack = array('fifth','second','third', 'first');

// Returns key 1 in haystack
$search = array_search( $needle, $haystack );

如果没有函数,接受可能是我可用于创建自定义函数的数组的针的任何其他函数?

4 个答案:

答案 0 :(得分:3)

这可能有助于建立你的功能:

$intersection = array_intersect($needle, $haystack);

if ($intersection) // $haystack has at least one of $needle

if (count($intersection) == count($needle)) // $haystack has every needle

答案 1 :(得分:2)

您可以使用array_intersect():http://php.net/manual/en/function.array-intersect.php

if (empty(array_intersect($needle, $haystack)) {
   //nothing from needle exists in haystack
}

答案 2 :(得分:1)

$needle = array('first', 'second');
$haystack = array('fifth','second','third', 'first');

// Returns key 1 in haystack


function array_needle_array_search($needle, $haystack)
{
        $results = array();
        foreach($needle as $n)
        {
                $p = array_search($n, $haystack);
                if($p)
                    $results[] = $p;
        }
        return ($results)?$results:false;
}

print_r(array_needle_array_search($needle, $haystack));

答案 3 :(得分:0)

$needle = array('first', 'second');
$haystack = array('fifth','second','third', 'first');

if(in_array($needle, $haystack)) {
     echo "found";
}