基于php中的键查找值的有效方法

use*_*007 4 php dictionary lookup-tables key-value

使用大约100,000个键/值对的列表(两个字符串,大多数每个大约5-20个字符),我正在寻找一种方法来有效地找到给定键的值.

这需要在php网站上完成.我熟悉java中的哈希表(这可能是我在java中工作时会做的),但我是php的新手.

我正在寻找关于如何存储此列表的提示(在文本文件或数据库中?)并搜索此列表.

该列表必须偶尔更新,但我最感兴趣的是查找时间.

Sha*_*obe 13

你可以把它做成一个直接的PHP数组,但是Sqlite将是你速度和方便的最好选择.

PHP数组

只需将所有内容存储在php文件中,如下所示:

<?php
return array(
    'key1'=>'value1',
    'key2'=>'value2',
    // snip
    'key100000'=>'value100000',
);
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样访问它:

<?php
$s = microtime(true); // gets the start time for benchmarking

$data = require('data.php');
echo $data['key2'];

var_dump(microtime(true)-$s); // dumps the execution time
Run Code Online (Sandbox Code Playgroud)

这不是世界上最有效的东西,但它会起作用.我的机器需要0.1秒.

源码

PHP应该启用sqlite,这对于这种事情很有用.

此脚本将从头到尾为您创建一个数据库,其特征与您在问题中描述的数据集类似:

<?php
// this will *create* data.sqlite if it does not exist. Make sure "/data" 
// is writable and *not* publicly accessible.
// the ATTR_ERRMODE bit at the end is useful as it forces PDO to throw an
// exception when you make a mistake, rather than internally storing an
// error code and waiting for you to retrieve it.
$pdo = new PDO('sqlite:'.dirname(__FILE__).'/data/data.sqlite', null, null, array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));

// create the table if you need to
$pdo->exec("CREATE TABLE stuff(id TEXT PRIMARY KEY, value TEXT)");

// insert the data
$stmt = $pdo->prepare('INSERT INTO stuff(id, value) VALUES(:id, :value)');
$id = null;
$value = null;

// this binds the variables by reference so you can re-use the prepared statement
$stmt->bindParam(':id', $id);
$stmt->bindParam(':value', $value);

// insert some data (in this case it's just dummy data)
for ($i=0; $i<100000; $i++) {
    $id = $i;
    $value = 'value'.$i;
    $stmt->execute();
}
Run Code Online (Sandbox Code Playgroud)

然后使用值:

<?php
$s = microtime(true);

$pdo = new PDO('sqlite:'.dirname(__FILE__).'/data/data.sqlite', null, null, array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));

$stmt = $pdo->prepare("SELECT * FROM stuff WHERE id=:id");
$stmt->bindValue(':id', 5);
$stmt->execute();

$value = $stmt->fetchColumn(1);

var_dump($value);

// the number of seconds it took to do the lookup
var_dump(microtime(true)-$s);
Run Code Online (Sandbox Code Playgroud)

这个更快.在我的机器上0.0009秒.

MySQL的

您也可以使用MySQL而不是Sqlite,但如果它只是一个具有您描述的特征的表,那么它可能会有点过分.如果您有可用的MySQL服务器,上面的Sqlite示例将使用MySQL正常工作.只需将实例化PDO的行更改为:

$pdo = new PDO('mysql:host=your.host;dbname=your_db', 'user', 'password', array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));
Run Code Online (Sandbox Code Playgroud)

sqlite示例中的查询应该可以正常使用MySQL,但请注意我没有测试过.

让我们有点疯狂:文件系统疯狂

并不是说Sqlite解决方案很慢(0.0009秒!),但这在我的机器上快了大约四倍.此外,Sqlite可能不可用,设置MySQL可能是不可能的,等等.

在这种情况下,您还可以使用文件系统:

<?php
$s = microtime(true); // more hack benchmarking

class FileCache
{
    protected $basePath;

    public function __construct($basePath)
    {
        $this->basePath = $basePath;
    }

    public function add($key, $value)
    {
        $path = $this->getPath($key);
        file_put_contents($path, $value);
    }

    public function get($key)
    {
        $path = $this->getPath($key);
        return file_get_contents($path);
    }

    public function getPath($key)
    {
        $split = 3;

        $key = md5($key);
        if (!is_writable($this->basePath)) {
            throw new Exception("Base path '{$this->basePath}' was not writable");
        }
        $path = array();
        for ($i=0; $i<$split; $i++) {
            $path[] = $key[$i];
        }
        $dir = $this->basePath.'/'.implode('/', $path);
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }
        return $dir.'/'.substr($key, $split);
    }
}

$fc = new FileCache('/tmp/foo');

/*
// use this crap for generating a test example. it's slow to create though.
for ($i=0;$i<100000;$i++) {
    $fc->add('key'.$i, 'value'.$i);
}
//*/

echo $fc->get('key1', 'value1');

var_dump(microtime(true)-$s);
Run Code Online (Sandbox Code Playgroud)

这个在我的机器上查找需要0.0002秒.无论高速缓存大小如何,这也具有合理恒定的优点.