Files
orico-official-website/app/admin/common.php
2025-02-20 16:13:06 +08:00

74 lines
2.5 KiB
PHP

<?php
// 这是系统自动生成的公共文件
if (!function_exists('array_to_tree')) {
/**
* 数组转换为树状结构
* @param array $data 数据
* @param int $pid 父级ID
* @param string $with 转换依据字段
* @param int $level 层级
* @return array
*/
function array_to_tree(array $data, int $pid, string $with = 'pid', int $level = 1)
{
$ret = [];
foreach ($data as $item) {
if ($item[$with] == $pid) {
$item['level'] = $level;
$children = array_to_tree($data, $item['id'], $with, $level + 1);
if ($children) {
$item['children'] = $children;
}
$ret[] = $item;
}
}
return $ret;
}
}
if (!function_exists('xlsx_writer')) {
/**
* 构建Excel数据
* @param array $data 数据 例:[['name'=>'张三','age'=>18, 'sex'=>'男']]
* @param array $schema 表头信息 例:['name' => '姓名', 'age' => '年龄', 'sex' => '性别']
* @param string $filename 下载文件名称 默认为YmdHis时间
* @return \PhpOffice\PhpSpreadsheet\Writer\IWriter
*/
function xlsx_writer(array|\think\model\Collection $data, array $schema, string $filename = ''): \PhpOffice\PhpSpreadsheet\Writer\IWriter
{
// 获取Spreadsheet对象
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// 写入表头
$title = array_values($schema);
$title_col = 'A';
foreach ($title as $value) {
// 单元格内容写入
$sheet->setCellValue($title_col . '1', $value);
$title_col++;
}
// 写入数据
$row = 2;
$keys = array_keys($schema);
foreach ($data as $item) {
$data_col = 'A';
foreach ($keys as $key) {
$sheet->setCellValue($data_col . $row, $item[$key] ?? '');
$data_col++;
}
$row++;
}
flush();
ob_flush();
if ($filename == '') $filename = date('YmdHis');
header('Access-Control-Expose-Headers: Content-Disposition');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; Charset=UTF-8');
header('Content-Disposition: attachment;filename=' . $filename . '.xlsx');
header('Cache-Control: max-age=0');
return \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
}
}