Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 425
Vilk Avatar asked Feb 14 '26 09:02

Vilk


1 Answers

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'],
        ],
    ]); ?>
like image 159
arkoak Avatar answered Feb 16 '26 23:02

arkoak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!