Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

php - Optimization of foreach for thousands items

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;

Code compares rows of two tables by someid. If it find coincidence it updates price column, if not creates a new record.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use CDataProviderIterator which:

... allows iteration over large data sets without holding the entire set in memory.

You first have to pass a CDataProvider instance to it:

$dataProvider = new CActiveDataProvider("Oldproduct");
$iterator = new CDataProviderIterator($dataProvider);
foreach($iterator as $item) {
    // do stuff
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...