有一种更好的方法来翻译使用 yii2tech\spreadsheet\Spreadsheet 的查询结果

There is a better way to translate the results of a query using yii2tech\spreadsheet\Spreadsheet

我正在进行手动查询。您可以轻松翻译列的名称,但我无法以稍微更有效的方式处理列的结果。在 yii2tech\spreadsheet\Spreadsheet.

的帮助下,结果打印在 excel 中

正在准备查询

$columns = [
  [
    'attribute' => 'description',
    'label' => Yii::t('data', 'Description')
  ],
  [
    'attribute' => 'type',
    'label' => Yii::t('data', 'Type')
  ]
];

$query
  ->addSelect(['description' => 'data.description'])
  ->addSelect(['type' => 'data.type'])
  ->from('data')

$rows = $query->all();

到目前为止,我进行了查询。以下是我翻译type栏结果的方法。因为它们可以只是一些值。

翻译结果

foreach ($rows as $key => $row) {
  $rows[$key]['type'] = Yii::t('data', $row['type']);
}

此数据导出为xls格式:

正在导出结果

$exporter = new Spreadsheet([
  'dataProvider' => new ArrayDataProvider([
    'allModels' => $rows,
  ]),
  'columns' => $columns,
]);

您可以在 $columns 声明中定义翻译 - 它将节省您通过结果数组的手动迭代以用翻译后的字符串替换类型:

$columns = [
    [
        'attribute' => 'description',
        'label' => Yii::t('data', 'Description'),
    ],
    [
        'attribute' => 'type',
        'label' => Yii::t('data', 'Type'),
        'value' => function ($data) {
            return Yii::t('data', $data['type']);
        }
    ],
];

如果 sheet 很大并且类型经常重复,您可以尝试缓存翻译后的字符串 - Yii::t() 可能相当昂贵:

$columns = [
    [
        'attribute' => 'description',
        'label' => Yii::t('data', 'Description'),
    ],
    [
        'attribute' => 'type',
        'label' => Yii::t('data', 'Type'),
        'value' => function ($data) {
            static $translations = [];
            if (!isset($translations[$data['type']])) {
                $translations[$data['type']] = Yii::t('data', $data['type']);
            }

            return $translations[$data['type']];
        },
    ],
];

这将对每个唯一类型仅调用一次 Yii::t()。但是,如果类型列表很小并且是硬编码的,您可以进一步简化它 - 创建 getTranslatedTypes() 静态方法,returns 翻译所有类型的列表:

public static function getTranslatedTypes() {
    return [
        'some type' => Yii::t('data', 'some type'),
        // ...
    ];
}

并将其用作翻译来源:

$translations = Type::getTranslatedTypes();
$columns = [
    [
        'attribute' => 'description',
        'label' => Yii::t('data', 'Description'),
    ],
    [
        'attribute' => 'type',
        'label' => Yii::t('data', 'Type'),
        'value' => function ($data) use ($translations) {
            return $translations[$data['type']] ?? $data['type'];
        },
    ],
];