如何迭代dataprovider对象?我想访问返回的每行的'name'字段并构建一个列表。你能帮忙吗?
表格/模型的表格结构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 ;
* 我的控制器类别中的功能 *
$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;
}
答案 0 :(得分:20)
试试这个:
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);
}
但是,您不需要使用数据提供程序,而只需使用模型
foreach(Categories::model()->findAll() as $record) {
答案 1 :(得分:14)
如果您需要大量数据收集并且担心内存使用,请执行以下操作:
$dataProvider = new CActiveDataProvider('Categories');
$iterator = new CDataProviderIterator($dataProvider);
foreach($iterator as $category) {
print_r($category);
}
CDataProviderIterator允许对大型数据集进行迭代,而无需将整个集合保存在内存中。
一些性能测试
Test Time (seconds) Memory (bytes) CDbDataReader 4.9158580303192 28339952 CActiveRecord::findAll() 5.8891110420227 321388376 CDataProviderIterator 6.101970911026 31170504
答案 2 :(得分:5)
在Yii2中,这也发生了变化:
$searchModel = new ModelSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
foreach($dataProvider->getModels() as $record) {
echo $record->id . '<br>';
}
exit();
参考:getModels()
答案 3 :(得分:4)
使用@ ben-rowe的解决方案,您可以立即查询所有行。你可能有内存问题。
使用以下解决方案,您将从十到十(默认CPagination.pageSize
值)获取类别:
$dataProvider = new CActiveDataProvider('Categories', array(
'pagination' => array(
'validateCurrentPage' => false
),
));
$pagination = $dataProvider->pagination;
while ($categories = $dataProvider->getData(true)){
foreach ($categories as $category) {
//...
}
$pagination->currentPage++;
}