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

I'm doing a manual query. You can translate the names of the columns easily, but I can not do it with the results of the columns in a slightly more efficient way. The results are printed in excel with the help of yii2tech\spreadsheet\Spreadsheet.

Preparing query

$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();

So far I make the query. The following is my way of translating the results of the type column. Because they can be just some values.

Translating results

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

This data is exported to xls format:

Exporting results

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

You may define translation inside of $columns declaration - it will save you manual iteration trough results array to replace type with translated string:

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

If sheet is big and types are often repeated, you may try to cache translated string - Yii::t() may be quite expensive:

$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']];
        },
    ],
];

This will call Yii::t() only once per unique type. But if list of types is small and hardcoded, you may simplify this even more - create getTranslatedTypes() static method, which returns translated list of all types:

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

And use it as a source of translations:

$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'];
        },
    ],
];