2

我有一个 php 文件,它将从 mysql_query() 检索到的结果编码为 json 格式。我收到的数据很大,即接近 200,000 个元组,其中每个元组有接近 10 个 varchar。早些时候,我遇到了一个异常,例如“允许的内存大小为 67108864 字节已用尽”。然后我在互联网上搜索,有人引用了 mysql_unbuffered_query 是解决方案。我也试过了,但我又遇到了同样的错误。我们如何在php中处理如此大的数据?

增加内存也不是一种选择,因为我有一个共享主机帐户。

这是我用于检索结果和编码为 json 的代码。

$result=mysql_unbuffered_query("Some query which gives large data");
$res=array();
if($result)
{
    while($r = mysql_fetch_assoc($result)) 
    {
        $rows[] = $r;
    }
    print json_encode($rows);

}
else
{
    echo mysql_error();
}

此类问题的解决方法是什么?

4

1 回答 1

2

像这样的东西是我想象的,只需添加您的查询等。

// Must be zero to get 1st record
$limit = 0;
// Determine how many you want to pull at a time
$offset = 10;
// Run count query to get this value
$total = 10000; // <- number of records needing to be pulled
for ($limit; $limit <= $total; $limit + $offset) {
    // Run query here and pump results into an array
    echo "Total: ".$total."<br>";
    echo "offset: ".$offset."<br>";
    echo "limit: ".$limit."<br>";
}

注意:确保您的总计数可以被您的偏移量整除,否则您将丢失记录,例如:

$offset = 19;
$total = 10000;

将最后一次调用输出为:

总计:10000
偏移量:19
限制:9994


编辑:

试试下面的模板,看看是否有帮助,当我运行我给出的原始答案时json_encode$limit + $offsetfor循环中我得到了相同的内存错误,但接下来的一点对我有用。

$offset = 10;
$total = 1000000;
$array = array();
for ($limit = 0; $limit <= $total; $limit++) {
    // Your code here
    $array[$limit] = $offset;
    // Keep the following line
    $limit = ($limit - 1) + $offset;
}
print json_encode($array);
于 2013-02-01T14:24:30.420 回答