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;
}
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) {
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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With