处理访问 JSON 文件的多个请求



我在文本中有 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代码,可以检查现有msisdn的json文件

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 条记录时,我们有一个读取超时。 由于我们的服务器上有一个巨大的请求,每小时大约 200k 个请求,从而提高了整个过程的效率。

任何人都可以提供解决方案或替代方法吗?

注意:我不能在这里使用数据库

您可以使用file()而不是fopen() and fclose()

function checkmsisdnallreadyexists($msisdn){ 
$file_array = file('give file path',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); 
foreach($file_array as $arr){ 
$msisdn_array = json_decode($arr,true); 
$msisdn_value = $msisdn_array['msisdn']; 
if($msisdn_value == $msisdn) { 
$date1=date_create($msisdn_array['subdate']); 
$date2=date_create(date('Y-m-d H:i:s')); 
$diff=date_diff($date1,$date2); 
if($diff->format('%a') < 31) { 
return true; 
} 
} 
} 
}

最新更新