1. 解释型语言的妙处之一,在于可以动态生成代码再调用执行~
2. 对于数据量不大(几千条?)的(key,value),存成数组文件,执行查找操作,效率应该是好于数据库操作的;
3. php的数组,是hash数组,默认情况下,key是0, 1, 2, ...
顺便说,这些是缺乏乐趣的工作,即使我觉得";"代表一个语句的结束已经天经地义;
不多说了,代码:
生成数组文件:
if (! file_exists($srcFilePath)) { return false; }
$info = array(); $srcInfo = file($srcFilePath); if (empty($srcInfo)) { return false; }
foreach ( $srcInfo as $line) { $line = trim($line); if ( empty($line) ) { continue; } list($key, $value) = explode(' ', $line); $cityInfo[$citycode] = $city; } $content = "<?php\n"; $content .= "\$myinfo = ". var_export($info, true) . ";\r\n"; $content .= "?>"; file_put_contents($cacheFilePath, $content);
|
查找
/* 通过key查找value */
include($cacheFilePath); if ( empty($myinfo) ) { return false; } if (isset($myinfo[$key])) { return $myinfo[$key]; } return "";
/*通过value查找key*/
include($cacheFilePath); if ( empty($myinfo) ) { return false; }
foreach ( $myinfo as $key => $value) { if ($value == $search_value) { return $key; } }
|