I am new to php and Yii and need some help regarding showing array in the webpage.

In the controller I open my e-mail inbox and iterate through the e-mails in inbox and build array with each e-mail address as key having values

if (array_key_exists($fromemail,$senders)) 
{ $senders[$fromemail]['rcount']++; }
else {
      $senders[$fromemail]['e-mail'] = $fromemail;
      $senders[$fromemail]['Name'] = $fromname;
      $senders[$fromemail]['rcount'] = 1;
$model->top_senders = $senders;

Then in the view file of Step2 I want to show the data in CGridview

if (isset($model->top_senders))
$gridDataProvider = new CArrayDataProvider($model->top_senders);
$gridColumns = array(
    array('name'=>'e-mail', 'header'=>'E-mail','value' =>'$data->e-mail'),
    array('name'=>'rcount', 'header'=>'# of mails','value'=>'$data->rcount'),);

$this->widget('bootstrap.widgets.TbGridView',array('dataProvider' => $gridDataProvider,'template' => "{items}",'columns'=>$gridColumns));

But I will get error during rendering of the table: PHP notice Undefined offset: 0

125      * Renders a data cell.
126      * @param integer $row the row number (zero-based)
127      */
128     public function renderDataCell($row)
129     {
130         $data=$this->grid->dataProvider->data[$row];

What I am doing wrong? Can anyone help me?

No correct solution


You should't add data to provider as follows: $gridDataProvider->setData($model->top_senders);

It added during initialization. You must be sure that the array has a key id, otherwise you need to specify it manually (it must be unique) as follows:

$gridDataProvider = new CArrayDataProvider($model->top_senders, array(

You will also need to make sure that the array $model->top_senders has the following structure:

    '0'=>array(...user data here),
    '1'=>array(...user data here),

If you var_dump($gridDataProvider->data) you'd notice there's no value for the 0th index in the array. This happens when you run some filter function on the array. Assuming there are 5 values in the filtered array, the filtered array would look something like this when var_dump'd.

array(5) {
    [1] => Object (Mailer) {…},
    [2] => Object (Mailer) {…},
    [4] => Object (Mailer) {…},
    [8] => Object (Mailer) {…},
    [9] => Object (Mailer) {…},

A filter operation on an array can leave the array looking like the above.

When the CGridView is trying to feed the view with data, it does it sequentially—this, I find, is a shortcoming in Yii and should be raised as an issue.

In order to fix this, use PHP's array_values() like so…

$properly_indexed_array = array_values($filtered_array);

This will copy the values of the filtered array into a new array. This is not the optimal solution in terms of memory. So far, I do not see any means in PHP other than this though.

You may then go ahead and set this as the data for your data provider like so…

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow