We might consider foreach to be painful and a headache while using it to deal with thousands or millions of records. Even more so if we have a nested foreach.
For example,
foreach ($parent as $parentData) {
// few conditional added here
$parentObj = $this->extract();
foreach ($chilren as $childrenData) {
if ($childrenData['id'] === $parentData['id']) {
$childrenObj = $this->extract();
$parentObj->setData($childrenObj);
// and even more evil things come here....
}
}
$parentObj->save();
}
In my situation, I have two foreach loops. And each one contains approximate 50,000 ~ 70,000 records. $parent and $children are parameters passed to the method.
The raw data source both of $parent and $children are CSV files. And I'm using yield to transform them to be traversable with foreach.
There is no trouble with yield.
If you concern about the code: https://stackoverflow.com/a/37342184/2932590
I tried to unset both of $parentObj and $childrenObj at the end of first foreach, but unfortunately it's not working. I also tried to use the references &$parentData, but the result is same.
How could I make this work?
I was advised to use SPL Iterators in this case. Can anyone please explain me how it works?