考虑这样的数组,
$sports = array('Football','cricket ball','tennis ball','shuttle bat','hockey stick');
我想从$ sports这样创建一个数组,
$ball = array('Football','cricket ball','tennis ball');
基于搜索键( 此处为'球' )。
如果循环遍历数组 $ sports 并逐个检查,将获得结果。但是,我已经在循环中,甚至可能循环超过50,000次。所以想到避免另一个循环。
还有其他方法可以完成这项工作吗?
由于
答案 0 :(得分:3)
尝试array_filter()
+ preg_match()
个函数:
<?php
header('Content-Type: text/plain; charset=utf-8');
$array = array('Football','cricket ball','tennis ball','shuttle bat','hockey stick');
$word = 'ball';
$results = array_filter(
$array,
function($value) use ($word){
return preg_match('/' . $word . '/i', $value);
}
);
print_r($results);
?>
节目:
Array
(
[0] => Football
[1] => cricket ball
[2] => tennis ball
)
答案 1 :(得分:2)
$sports = array('Football','cricket ball','tennis ball','shuttle bat','hockey stick');
$input = 'ball';
$result = array_filter($sports, function ($item) use ($input) {
if (stripos($item, $input) !== false) {
return $item;
}
});
print_r($result);