Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over Yii CActiveDataProvider object?

Tags:

html

php

mysql

yii

How to iterate over a dataprovider object? I want to access the 'name' field of each row returned and build a list. Can you help?

Table structure for table/model categories

CREATE TABLE IF NOT EXISTS `categories` (
  `idCategory` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(64) NOT NULL,
  PRIMARY KEY (`idCategory`) USING BTREE
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=55 ;

*Function in my Controller Categories*

    $names = array();
    public function returnCategoryNames()
{
    $dataProvider= new CActiveDataProvider('Categories');
    $dataProvider->setPagination(false);
    $count = $dataProvider->totalItemCount();

    for($i = 0; $i < $count; $i++){

             // this is where I am lost...
             $myname = $dataProvider->data[$i]->name;
             array_push($names, $myname);

    }   

       return $names;

}
like image 598
eric Avatar asked Aug 29 '12 02:08

eric


3 Answers

Try this:

public function returnCategoryNames()
{
  $dataProvider= new CActiveDataProvider('Categories');
  $dataProvider->setPagination(false);
  //$count = $dataProvider->totalItemCount();
  $names = array();
  foreach($dataProvider->getData() as $record) {
    $names[] = $record->name;
  }
  return array_unique($names);
}

However you dont need to use a data provider, instead just use the model

foreach(Categories::model()->findAll() as $record) {
like image 80
Ben Rowe Avatar answered Nov 09 '22 10:11

Ben Rowe


If you need itarate large data collection and you worry about memory usage do this:

$dataProvider = new CActiveDataProvider('Categories');
$iterator = new CDataProviderIterator($dataProvider);
foreach($iterator as $category) {
   print_r($category);
}

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

some performance tests

Test                        Time (seconds)          Memory (bytes)
CDbDataReader               4.9158580303192         28339952
CActiveRecord::findAll()    5.8891110420227         321388376
CDataProviderIterator       6.101970911026          31170504
like image 14
Achim Krauß Avatar answered Nov 09 '22 09:11

Achim Krauß


In Yii2 this has changed too:

    $searchModel = new ModelSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    foreach($dataProvider->getModels() as $record) {
        echo $record->id . '<br>';
    }

    exit();

Reference: getModels()

like image 5
Coz Avatar answered Nov 09 '22 10:11

Coz