[英]Partial match search of an array in PHP
我試圖在多維數組中搜索部分字符串。 我的數組如下所示:
$data = array(
"United Kingdom" => array(
"AFXX0001" => "Nottingham",
"AFXX0002" => "Notting Hill",
),
"Germany" => array(
"ALXX0001" => "Garnottheinem",
"ALXX0002" => "Tirane",
),
);
我正在嘗試構建一個搜索功能,該功能將顯示滿足部分匹配要求的所有結果。 到目前為止,我的函數如下所示:
function array_find( $needle, $haystack )
{
foreach ($haystack as $key => $array) {
foreach ( $array as $key2 => $value ) {
if (false !== stripos($needle, $value)) {
$result = $key . ' ' . $value . ' ' . $key2;
return $result;
}
}
}
return false;
}
它有效,但是僅當我輸入實際值時,例如array_find( 'Nottingham', $data );
。
如果我這樣做array_find( 'nott', $data );
我希望它返回Nottingham,Notting Hill和Garnottheinem,但是它返回bool(false)
。
在stripos()調用中,針和干草堆被顛倒了。
然后連接結果列表。
嘗試這個:
function array_find( $needle, $haystack )
{
$result = ''; //set default value
foreach ($haystack as $key => $array) {
foreach ( $array as $key2 => $value ) {
if (false !== stripos($value,$needle)) // hasstack comes before needle
{
$result .= $key . ' ' . $value . ' ' . $key2 . '<br>'; // concat results
//return $result;
}
}
}
return $result;
}
發生錯誤:
if (false !== stripos($needle, $value)) {
解:
if (false !== stripos($value, $needle)) {
$data = array(
"United Kingdom" => array(
"AFXX0001" => "Nottingham",
"AFXX0002" => "Notting Hill",
),
"Germany" => array(
"ALXX0001" => "Garnottheinem",
"ALXX0002" => "Tirane",
),
);
$search = 'not';
$result = array();
array_walk_recursive(
$data,
function($item, $key) use ($search, &$result){
$result[$key] = (stripos($item, $search) !== false) ? $item : null;
}
);
$result = array_filter(
$result
);
var_dump($result);
使用SPL迭代器而不是array_walk_recursive()的等效方法
$result = array();
foreach (new RecursiveIteratorIterator(
new RecursiveArrayIterator($data),
RecursiveIteratorIterator::LEAVES_ONLY
) as $key => $value) {
echo $key,PHP_EOL;
$result[$key] = (stripos($item, $search) !== false) ? $item : null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.