I have an array like
Array (
[4621] => Hall Enstein
[4622] => Function Areas
[4623] => Dining Areas
[4624] => Events
[4625] => Galleries
[4626] => Custom Pages
[4627] => News
[4629] => Promotions
);
How to get result like [4622] => Function Areas
with the search keyword like f
or fu
. I use array_intersect()
function for this requirment. But here I have to search with the keyword "Function Areas"
, not f
or fu
. With f
or fu
, search result [4622] => Function Areas
is not coming. If any one know it, please help me. Thank you
You could use array_filter()
to filter the array:
$output = array_filter($yourArray, function($v) {
return stristr($v, 'fu');
});
Would output:
array
4622 => string 'Function Areas' (length=14)
There is no standard function to search for a partial match within the array values. You need to define a function here is a handy one using the array_filter function mentioned by @billyonecan:
function array_match_string($haystack, $needle){
return array_filter($haystack, function($value) use ($needle){
return stripos($value, $needle) !== false;
});
}
You can than simply call the function with an array and a string to search for:
$result_array = array_match_string($array, 'fu');
Solution with PHP < 5.3 (we need a global helper variable to be visible in the callback):
function array_match_string_pre_php_53($haystack, $needle){
global $_array_match_string_needle;
$_array_match_string_needle = $needle;
return array_filter($haystack, 'array_match_string_callback');
}
function array_match_string_callback($value){
global $_array_match_string_needle;
return strpos($value, $_array_match_string_needle) !== false;
}
$result_array = array_match_string_pre_php_53($array, 'Fu');
You can try searching with strpos which returns position of found given keyword and -1 if string does not contain keyword
$fruits = array('apple', 'banana', 'orange');
$found = array(); // every that matches keyword
$keyword = "e"; //searching for letter e
foreach($array as $fruit)
{
if(stripos($fruit, $keyword) !== -1)
{
array_push($found, $fruit);
}
}
// fruits should now contain apple and orange
Note that code wasn't tested so it can contain syntax errors but principle should work
此要求的另一种方式是,必须在该数组处于循环状态的循环中移动该数组。
$keyword = strtolower(trim($needle)); foreach($array as $key=>$arrayvalue) { $isExists = @preg_match("/$keyword/", $arrayvalue); if($isExists) { $com = sprintf('%s [nid: %d]', ucwords($arrayvalue), $key); $spresults[$com] = ucwords($arrayvalue); } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.