以下是JSON文件的一部分。
{
"products": {
"product" : [
{ "name" : "Desktop", "price" : 799.99, "memory" : "4GB"},
{ "name" : "Laptop", "price" : 999.99, "memory" : "3GB"},
{ "name" : "Notebook", "price" : 899.99, "memory" : "2GB"}
] }}
我需要解析一个非常大的JSON文件,然后根据用户查询显示相关的搜索结果。我想避免使用json_decode或file_get_contents将整个文件加载到内存中,而是逐行解析该文件。
$search_results = "";
$Json_file = fopen("products.json", "r");
while (!feof($Json_file)) {
$line_of_data .= fgets($Json_file);
$decoded_line = json_decode($line_of_data);
现在,我想使用 if 语句,以便 fgets() 函数只从 JSON 文件中获取“价格”值在900以下的数据。下面的 if 语句无法正常工作-它会导致页面完全空白,但是没有 if 语句时代码可以正常工作。我的问题是:有没有一种“性能友好”的编码方式(在代码的这个位置),使得无关的 JSON 数据可以被过滤掉,不会被放入下面的 search_results 变量中?或者有没有更好的方法来逐行解析大型 JSON 文件?
if ($decoded_line->products->product->price < 900) { //assuming a site visitor is searching for an item under $900
$search_results .= decoded_line->products->product;
}
}
通过在上面的if语句中过滤掉不相关的JSON数据,我认为当我们在此处使用json_decode时会有助于整体性能。
$data = json_decode($search_results);
$product = $data->products->product;
foreach($product as $Product) {
echo $Product->name . " " . $Product->price;
echo "<br>";
}
fclose($Json_file);
非常感谢您提供的建议!