I have created an array in php.
Array ( [0] => Array ( [ip_addr] => 152.12.40.205 [Management_col-2] => Success [Management_col-3] => Success ) [1] => Array ( [ip_addr] => 152.12.40.206 [Management_col-2] => Success [Management_col-3] => Error ) [2] => Array ( [ip_addr] => 152.12.40.207 [Management_col-2] => NA [Management_col-3] => Success ) [3] => Array ( [ip_addr] => 152.12.40.209 [Management_col-2] => Success [Management_col-3] => Success ) );
I will have dynamic columns like ip_addr, Management_col-2, ….and so on with there respective dynamic values.
I want to use it in Grid view of YII.
$nc3DataProvider = new CArrayDataProvider($alldata); $this->widget('zii.widgets.grid.CGridView', array( 'id' => 'nc3-audit-grid', 'dataProvider' => $nc3DataProvider, ));
I also want to use filter on the table.
Plz help me for this.
Thank you so much in advance.
Advertisement
Answer
You can use CArrayDataProvider this a sample
Controller
public function actionGridViewArray() { $rawData=array( array('id'=>1, 'username'=>'from', 'email'=>'array'), array('id'=>2, 'username'=>'test 2', 'email'=>'hello@example.com'), ); // or using: $rawData=User::model()->findAll(); $arrayDataProvider=new CArrayDataProvider($rawData, array( 'id'=>'id', /* 'sort'=>array( 'attributes'=>array( 'username', 'email', ), ), */ 'pagination'=>array( 'pageSize'=>10, ), )); $params =array( 'arrayDataProvider'=>$arrayDataProvider, ); if(!isset($_GET['ajax'])) $this->render('grid_view_array', $params); else $this->renderPartial('grid_view_array', $params); }
View (gridview)
$this->widget('zii.widgets.grid.CGridView', array( 'dataProvider' => $arrayDataProvider, 'columns' => array( array( 'name' => 'username', 'type' => 'raw', 'value' => 'CHtml::encode($data["username"])' ), array( 'name' => 'email', 'type' => 'raw', 'value' => 'CHtml::link(CHtml::encode($data["email"]), "mailto:".CHtml::encode($data["email"]))', ), ), ));
And buildin the column dinamically
foreach ($header as $cols){ $column[] = array( 'name'=> $cols, 'value'=>'isset($data[''.$cols.''])?$data[''.$cols.'']:""', ); } $this->widget('zii.widgets.grid.CGridView', array( 'dataProvider' => $arrayDataProvider, 'columns' => $column ));