【问题标题】:How to display array data in Yii2 GridView using ActiveDataprovider?如何使用 ActiveDataprovider 在 Yii2 GridView 中显示数组数据?
【发布时间】:2018-07-11 16:21:18
【问题描述】:

在我的数据库中,

"email" : [ 
    "amnop@mailinator.com", 
    "abc@mail.com"
],

当我print_r($model->email)时, 它显示了

Array ( [0] => amnop@mailinator.com [1] => abc@mail.com )

在我的 GridView 中,

<?= GridView::widget([
        'dataProvider' => $dataProvider,
        ----
        'columns' => [
                     -----
                    'price',
                    [
                         'attribute' => 'email',
                          'value' => function($model) {
                              //I need help here... I prefer any foreach function
                        }
                    ],

                    -----
        ]
?>

我必须在同一列中显示所有电子邮件。如何做到这一点?

编辑

我使用 ActiveDataprovider 从我的数据库中获取值。

【问题讨论】:

    标签: arrays gridview yii2


    【解决方案1】:

    根据你想要达到的目标,你可以直接分解 emails 数组:

    [
         'attribute' => 'email',
         'value' => function($model) {
              if (is_array($model->email)) {
                  return implode(', ', $model->email);
              }
    
              return $model->email;
        }
    ],
    

    【讨论】:

    • 收到错误implode(): Invalid arguments passed
    • @BeginnerDev 这是一个错字,请尝试更新版本的答案。
    • 你确定$model-&gt;email 是一个数组吗?通过额外检查尝试我的更新。
    【解决方案2】:

    假设你是一个数组

    $data = [
        ['email' => 'amnop@mailinator.com'],
        ['email' => 'abc@mail.com'],
        ...
        ['email' =>  'youremail100@mail.com'],
    ];
    

    您可以使用 ArrayDataProvider

    $provider = new ArrayDataProvider([
        'allModels' => $data,
        'pagination' => [
            'pageSize' => 10,
        ],
        'sort' => [
            'attributes' => [ 'email'],
        ],
    ]);
    

    像往常一样发送数据提供者

    所以在gridview中你可以使用,

      <?= GridView::widget([
              'dataProvider' => $dataProvider,
              ----
              'columns' => [
                           -----
                          'price',
                          [
                               'attribute' => 'email',
                                'value' => function($model) {
                                    //I need help here...
                              }
                          ],
    
                          -----
              ]
      ?>
    

    你可以看看yii2指南https://www.yiiframework.com/doc/guide/2.0/en/output-data-providers 和文档https://www.yiiframework.com/doc/api/2.0/yii-data-arraydataprovider

    【讨论】:

    • 如何在我的搜索模型中初始化 $data?
    • 你的评论有问题吗?或评论...?请解释
    • 数组数据提供程序用于数组数据源..广告您应该构建一个适当的数组作为具有列名和值的数组的集合..如果您需要来自 db 的数据,您可以使用 sqldataprovider或指南链接中的 activedataprovider
    • 您是否定义了具有适当内容的数组 $data .for 配置 arrayDataProvider ? ..我建议您深入查看指南.in链接..并深入了解相关概念。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 2016-07-12
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多