$example = array('An example','Another example','Last example');
Run Code Online (Sandbox Code Playgroud)
如何在上面的数组中松散搜索"Last"一词?
echo array_search('Last example',$example);
Run Code Online (Sandbox Code Playgroud)
如果针与值中的所有内容完全匹配,上面的代码将仅回显值的键,这是我不想要的.我想要这样的东西:
echo array_search('Last',$example);
Run Code Online (Sandbox Code Playgroud)
如果值包含单词"Last",我希望值的键回显.
Ale*_*s G 54
要查找符合搜索条件的值,您可以使用以下array_filter
函数:
$example = array('An example','Another example','Last example');
$searchword = 'last';
$matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); });
Run Code Online (Sandbox Code Playgroud)
现在$matches
数组将只包含原始数组中包含单词last(不区分大小写)的元素.
如果需要查找与条件匹配的值的键,则需要循环遍历数组:
$example = array('An example','Another example','One Example','Last example');
$searchword = 'last';
$matches = array();
foreach($example as $k=>$v) {
if(preg_match("/\b$searchword\b/i", $v)) {
$matches[$k] = $v;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,数组$matches
包含原始数组中的键值对,其中值包含(不区分大小写)单词last.
Way*_*tty 19
function customSearch($keyword, $arrayToSearch){
foreach($arrayToSearch as $key => $arrayItem){
if( stristr( $arrayItem, $keyword ) ){
return $key;
}
}
}
Run Code Online (Sandbox Code Playgroud)
$input= array('An example','Another example','Last example');
$needle = 'Last';
$ret = array_keys(array_filter($input, function($var) use ($needle){
return strpos($var, $needle) !== false;
}));
Run Code Online (Sandbox Code Playgroud)
这将为您提供其值包含针的所有键.