查表法 , PHP 把 array 存進 file

好處是, 下次直接把檔讀進 array 立即可查詢, 如果資料不常改變, 查詢頻率普通時用

// init my dict. keys and cache array to disk

if (!file_exists($arraypath)) {

  if ($handle) {

    while (!feof($handle)) {

      $buffer = trim(fgets($handle));

      $my_dict[$buffer] = 0;

    }

    fclose($handle);

  }

  $serialized = serialize($my_dict);

  $handle = fopen($arraypath, 'w');

  if ($handle) {

    fwrite($handle, $serialized);

    fclose($handle);

  }

} else {

  $handle = fopen($arraypath, 'r');

  if ($handle) {

    $my_dict = unserialize(fread($handle, filesize($arraypath)));

    fclose($handle);

  }

}