[英]filter values from an array similar to SQL LIKE '%search%' using PHP
[英]PHP : Search array similar DB “ like %key% ”
我有這種格式的數組:
countries(
[0] = Array
(
[0] = 1
[1] = USA
)
[1] = Array
(
[0] = 93
[1] = Afghanistan
)
[2] = Array
(
[0] = 358
[1] = Finland
)
)
=======
[0] country code
[1] country name
我想搜索此數組以獲取數字所屬的國家/地區。
例如:358545454554,我如何搜索數組以獲取哪個國家,在這種情況下=芬蘭,請考慮性能,所以我想以最快的方式
要匹配前幾個數字,請將這些數字的子字符串與結果進行比較:( demo )
<?php
$search = '358545454554';
$countries = [[1, 'USA'], [93, 'Afghanistan'], [358, 'Finland']];
$country = null;
foreach ($countries as $c) {
if (substr($search, 0, strlen($c[0])) == $c[0]) {
$country = $c[1];
break;
}
}
echo ($country === null) ? 'No country found!' : $country;
if (strpos($string, $word) === FALSE) {
... not found ...
}
請注意, strpos
區分大小寫,如果要進行不區分大小寫的搜索,請改用stripos()
。
還請注意===
,強制進行嚴格的相等性測試。 如果“ needle”字符串位於“ haystack”的開頭,則strpos
返回有效的0。 通過強制檢查實際的布爾假(也稱為0),可以消除該假positiv
$countries = array(
array('1','USA'),
array('93','Afghanistan'),
array('358','Finland'),
array('3','India')
);
$input_code = '358545454554';
$searched = array();
foreach($countries as $country) {
if (strpos($input_code, $country[0]) !== FALSE)
$searched[] = $country[1];
}
print_r($searched);
請訪問這里( 演示 )。
您可以為此使用array_filter。 第一個變體在國家/地區ID中的任意位置搜索數字,因此3581545454554與美國和Finnland匹配,第二個變體使用正則表達式僅過濾以相同數字開頭的ID。
$data = array(
array(1, 'USA'),
array(93, 'Afghanistan'),
array(358,'Finland')
);
$term = '358545454554';
// in case you want to match it anywhere in the term string...
$result = array_filter($data, function($elem) use($term) {
return (strpos((string) $term,(string) $elem[0]) !==false ) ? true : false;
});
var_dump($result);
// in case you want to match only from start
$result = array_filter($data, function($elem) use($term) {
return preg_match('/^'.$elem[0].'/',$term);
});
var_dump($result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.