【发布时间】:2019-03-31 03:41:33
【问题描述】:
我有一个带有示例数据的文本中的 json 文件
{"msisdn":"xxxxxxxxxx","productID":"YYYYYYYY","subdate":"2018-09-28 16:30:35","Status":"1"}
{"msisdn":"xxxxxxxxxx","productID":"YYYYYYYY","subdate":"2018-09-28 16:30:35","Status":"1"}
我有一个 php 代码可以检查 json 文件中是否存在现有 msisdn
class JSONObject implements JsonSerializable
{
public function __construct($json = false)
{
if ($json)
$this->set(json_decode($json, true));
}
public function set($data)
{
foreach ($data AS $key => $value) {
if (is_array($value)) {
$sub = new JSONObject;
$sub->set($value);
$value = $sub;
}
$this->{$key} = $value;
}
}
public function jsonSerialize()
{
return (object) get_object_vars($this);
}
}
function checkmsisdnallreadyexists($file,$msisdn)
{
if (is_file($file)) {
if (($handle = fopen($file, 'r'))) {
while (!feof($handle)) {
$line = trim(fgets($handle));
$jsonString = json_encode(json_decode($line));
// Here's the sweetness.
//$class = new JSONObject($jsonString);
$class = new JSONObject($jsonString);
if($class->msisdn == $msisdn)
{
$date1=date_create($class->subdate);
$date2=date_create(date('Y-m-d H:i:s'));
$diff=date_diff($date1,$date2);
if($diff->format('%a') < 31)
{
fclose($handle);
return true;
}
}
}
fclose($handle);
}
}
return false;
}
最初一切正常,但是当我的 json 文件有超过 30 000 条记录时,我们会出现读取超时。因为我们在我的服务器上有一个巨大的请求,每小时大约 20 万个请求,从而提高了整个过程的效率。
谁能提供解决方案或替代方法?
注意:这里不能使用数据库
【问题讨论】:
-
你可以试试
file(...)而不是fopen() ... fclose()。它只读取文件,您可以处理数据而不会阻塞文件超过必要的时间。 -
感谢您的帮助