PHP - 最有效的字典代码

Pam*_*ela 2 php arrays dictionary

我正在使用以下代码从制表符分隔的文件中提取单词的定义,只有两列(单词,定义).这是我尝试做的最有效的代码吗?

<?php
$haystack  = file("dictionary.txt");
$needle = 'apple';

$flipped_haystack = array_flip($haystack);

foreach($haystack as $value)
    {
    $haystack = explode("\t", $value);

    if ($haystack[0] == $needle)
        {
        echo "Definition of $needle: $haystack[1]";
        $defined = "1";
        break;
        }
    }

if($defined != "1")
    {
    echo "$needle not found!";
    }
?>
Run Code Online (Sandbox Code Playgroud)

Mar*_*c B 5

现在你正在做很多毫无意义的工作

1) load the file into a per-line array
2) flip the array
3) iterate over and explode every value of the array
4) test that exploded value
Run Code Online (Sandbox Code Playgroud)

你不能真正避免第1步,但为什么你必须为2和3做所有无用的"忙碌工作"?

例如,如果您的字典文本设置如下:

word:definition
Run Code Online (Sandbox Code Playgroud)

然后一个简单的:

$matches = preg_grep('/^$word:(.*)$/', $haystack);
Run Code Online (Sandbox Code Playgroud)

会为你做的伎俩,代码少得多.