【问题标题】:php selecting hash using wildcardsphp使用通配符选择哈希
【发布时间】:2011-02-05 23:25:52
【问题描述】:

假设我有一个哈希图,

$hash = array('fox' => 'some value',
              'fort' => 'some value 2',
              'fork' => 'some value again);

我正在尝试完成自动完成功能。当用户键入“fo”时,我想通过 ajax 从 $hash 中检索 3 个键。当用户键入“for”时,我只想检索键 fort 和 fork。这可能吗?

我的想法是使用二进制搜索来隔离带有“f”的键,而不是蛮力搜索。然后在用户键入查询时继续消除索引。有没有更有效的解决方案?

编辑:关于通配符,我想知道是否有办法执行 $hash["f*"],返回所有以 'f' 开头的索引。

【问题讨论】:

    标签: php hashmap string-matching


    【解决方案1】:

    这应该可以解决问题:

    $matches = preg_grep('/^for/', array_keys($hash));
    

    你最终会得到

    $matches[0] = 'fort';
    $matches[1] = 'fork'
    

    您可以从中引用原始的 $hash 数组。

    【讨论】:

    • 诅咒!你的答案比我写的要好! (+1)
    • 只要确保您使用的是 preg_quote!
    猜你喜欢
    • 2019-10-10
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    相关资源
    最近更新 更多