php - 处理访问 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 条记录时,我们有一个读取超时。因为我们在我的服务器上有一个巨大的请求,每小时大约 20 万个请求,从而提高了整个过程的效率。
任何人都可以提供解决方案或替代方法吗?
注意:我不能在这里使用数据库
解决方案
您可以使用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;
}
}
}
}
推荐阅读
- c# - '图像解码失败。提供的图像必须是位图' - Google Map Marker 上的 SetIcon 引发错误
- google-cloud-platform - 如何在goole云中将巨大的json从实例传输到Bigtable
- clojure - 使用“时间”测量在 Clojure 中的未来内部执行的进程的时间
- python - 如何通过 python 格式化我的 pandas 数据框以获取 csv 输出中的列?
- javascript - 您如何唯一地定位函数实例的 html/css?
- css - Flexbox:如何让子 1 具有其内容的宽度,而子 2 填充其余的宽度
- jquery - 提交表单后如何在就绪事件中传递函数
- system - 如何修复“VSTest.Console.exe”不被识别为内部或外部命令
- java - 在创建的 sqlite 数据库中更新整行(包含多列)
- c# - 匹配委托没有过载