Vilk
Vilk

Reputation: 162

Yii2 GridView multidimensional array

I got array:

123 => [
    "2015-09-01" => ["sum"=>"1030","count"=>"4"],
    "2015-09-02" => ["sum"=>"10","count"=>"24"],
    "2015-09-03" => ["sum"=>"120","count"=>"34"],
    "2015-09-04" => ["sum"=>"200","count"=>"45"]
    ],
124 => [
    "2015-09-01" => ["sum"=>"132","count"=>"48"],
    "2015-09-02" => ["sum"=>"10","count"=>"24"],
    "2015-09-03" => ["sum"=>"120","count"=>"34"],
    "2015-09-04" => ["sum"=>"200","count"=>"45"]
    ],

Now i like display this in GridView to get table like this:

--------------------------------------------
| ID | 2015-09-01 | 2015-09-02 | 2015-09-03|
|    |-------------------------------------|
|    | sum  |count| sum |count | sum |count|
|------------------------------------------|
|123 |1030  | 4   | 10  | 24   |120  | 34  |
|------------------------------------------|
|124 |132   | 48  | 10  | 24   |120  | 34  |
--------------------------------------------

Question how to get such an effect ?

Upvotes: 3

Views: 1321

Answers (1)

arkoak
arkoak

Reputation: 2497

For a 2d array with numbered rows, each row containing an array of elements, the following implementation is quite trivial.

1. Initialize the data provider

First initialize the array data provider in your controller by passing the data in allModels parameter. mode details of ArrayDataProvider can be found here

$dataProvider = new ArrayDataProvider([
            'allModels'=> $your2darray,
            'pagination' => [
                'pageSize' => 10,
            ],
        ]);

2. Display the Grid

Assuming you have passed the above data provider variable, in your view , use it in the grid as below, specifying whatever column to be displayed.

<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'id',
            'field1', 
             ...
            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

Upvotes: 1

Related Questions