在PHP中部分匹配搜索数组

时间:2014-07-16 16:25:21

标签: php arrays

我试图在多维数组中搜索部分字符串。我的数组看起来像这样:

$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)

3 个答案:

答案 0 :(得分:2)

在你的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;
}

答案 1 :(得分:2)

行错误:

if (false !== stripos($needle, $value)) {

解决方案:

if (false !== stripos($value, $needle)) {

答案 2 :(得分:1)

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