2011-04-12 92 views
2

是否有任何函數可以完成數組$ array的等價操作?像,這將是一個理想的解決方案:PHP array_search

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

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

如果沒有的功能,接受針任何其他功能,這可能是我可以用它來創建自定義函數數組?

回答

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
$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)); 
0
$needle = array('first', 'second'); 
$haystack = array('fifth','second','third', 'first'); 

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