Reputation: 61
Seeking your help to convert one big array with PHP generators. Below is my code for which I need rework: I am getting a result set from a service call and assigning all to an array:
foreach ($objects->result as $pointStdObject) {
$pointStdObjects[] = $pointStdObject;
}
This piece of code is inside a while loop which queries for records with an offset of 1000. Issue is $pointStdObjects[] tends to get very huge and I get PHP out of memory exception.
Later I again need to use this same array as:
foreach ($pointStdObjects as $pointStdObject) {
$point = $this->pointFactory->createPointFromStdObject($pointStdObject);
if (!$point) {
continue;
}
$points[] = $point;
}
return $points;
Please suggest if we can leverage PHP generators or yield here
Upvotes: 1
Views: 571
Reputation: 351
function getStd()
{
///your code before that
foreach ($objects->result as $pointStdObject) {
yield $pointStdObject;
}
}
function useStd()
{
foreach (getStd() as $pointStdObject) {
$point = $this->pointFactory->createPointFromStdObject($pointStdObject);
if (!$point) {
continue;
}
$points[] = $point;
}
return $points;
}
Upvotes: 2