PHP中数组的部分匹配搜索


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 );,我希望它返回诺丁汉、诺丁山和加诺特纳姆,但它返回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_recurive((的等效程序

$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;
}