本文介紹了千篇一律的foreach優化的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在對一組 25,000 結果運行下面的代碼.我需要優化它,因為我達到了內存限制.
I'm running the code below over a set of 25,000 results. I need to optimize it because i'm hitting the memory limit.
$oldproducts = Oldproduct::model()->findAll(); /*(here i have 25,000 results)*/
foreach($oldproducts as $oldproduct) :
$criteria = new CDbCriteria;
$criteria->compare('`someid`', $oldproduct->someid);
$finds = Newproduct::model()->findAll($criteria);
if (empty($finds)) {
$new = new Newproduct;
$new->someid = $oldproduct->someid;
$new->save();
} else {
foreach($finds as $find) :
if ($find->price != $oldproduct->price) {
$find->attributes=array('price' => $oldproduct->price);
$find->save();
}
endforeach;
}
endforeach;
代碼通過someid比較兩個表的行.如果發現巧合,它會更新 price 列,否則會創建一個新記錄.
Code compares rows of two tables by someid. If it find coincidence it updates price column, if not creates a new record.
推薦答案
使用 CDataProviderIterator
其中:
Use CDataProviderIterator
which:
... 允許對大型數據集進行迭代,而無需將整個數據集保存在內存中.
... allows iteration over large data sets without holding the entire set in memory.
您首先必須將 CDataProvider
實例傳遞給它:
You first have to pass a CDataProvider
instance to it:
$dataProvider = new CActiveDataProvider("Oldproduct");
$iterator = new CDataProviderIterator($dataProvider);
foreach($iterator as $item) {
// do stuff
}
這篇關于千篇一律的foreach優化的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!