我在 PHP(5.6) 中有一个非常大的动态生成的数组,希望将其转换为 JSON。问题是,这个数组太大了,无法全部加载到内存中 - 当我尝试处理它时会出现致命错误 (内存不足)。因此,我想到使用生成器可以解决内存问题。
这是我目前尝试过的代码 (这个简化的示例显然没有引起内存错误):
<?php
function arrayGenerator()// new way using generators
{
for ($i = 0; $i < 100; $i++) {
yield $i;
}
}
function getArray()// old way, generating and returning the full array
{
$array = [];
for ($i = 0; $i < 100; $i++) {
$array[] = $i;
}
return $array;
}
$object = [
'id' => 'foo',
'type' => 'blah',
'data' => getArray(),
'gen' => arrayGenerator(),
];
echo json_encode($object);
但是 PHP 似乎无法将生成器中的值进行 JSON 编码。这是我从之前脚本中得到的输出:
{
"id": "foo",
"type": "blah",
"data": [// old way - OK
0,
1,
2,
3,
//...
],
"gen": {}// using generator - empty object!
}
在调用json_encode
之前,是否有可能对由生成器产生的数组进行JSON编码,而不必生成完整序列?
iterator_to_array(arrayGenerator())
。 - apokryfos