У нас есть веб-сайт на основе PHP, который генерирует CSV-экспорт на основе выбора файлов Markdown. Мы можем выбрать файлы за месяц и экспортировать их таким образом.
Мы пытаемся создать заголовки CSV следующим образом:
- Включает каждый заголовок динамически во все файлы уценки
- Включает заголовки в том же порядке каждый месяц, если это возможно
Несколько простых примеров файлов уценки:
Файл 1:
b: 'value'
c: 'value'
d: 'value'
Файл 2:
a: 'value'
b: 'value'
d: 'value'
Файл 3:
a: 'value'
c: 'value'
d: 'value'
Экспортируя их в CSV, я надеялся, что заголовки будут
а | б | с | д
Так как на лету выяснилось бы, что
- Файл 1. c всегда после b, d всегда после c
- Файл 2. a всегда перед b, d всегда после b
- Файл 3. a всегда перед c (уже сейчас), c перед d
Может быть, я слишком усложняю эту часть.
Я заранее прошу прощения, если я не разъяснил это ясно. Я исследовал array_unique
и array_merge
, но я не уверен, поможет ли какой-либо из них мне достичь моей цели здесь.
Существующая функция такова:
/**
* Handle the request if requesting a group is exported to CSV
*/
public function exportGroupToCsv($year=null,$month=null)
{
/** @var Uri $uri */
$uri = $this->grav['uri'];
$segments = $uri->paths();
$typePath = $this->getTypePath($segments[2]);
if (!is_dir($typePath)) {
throw new \RuntimeException('No data found', 404);
}
$headers = [];
$rows = [];
/** @var \SplFileInfo $file */
foreach (new \FilesystemIterator($typePath) as $file) {
$thisyear = substr($file->getFilename(), 2,2);
$thismonth = substr($file->getFilename(), 4,2);
$thisdate = substr($file->getFilename(), 6,2);
$thishour = substr($file->getFilename(), 9,2);
$thisminute = substr($file->getFilename(), 11,2);
$thissecond = substr($file->getFilename(), 13,2);
if(!$year || ($thisyear == $year && $thismonth == $month)){
$record = Yaml::parse(File::instance($file->getPathname())->content());
if (empty($headers)) {
$headers = array_merge(['Date'], array_keys($record));
}
$sortedRow = [];
foreach ($headers as $key) {
if($key == 'Date'){
$sortedRow[$key] = $thismonth."/".$thisdate."/".$thisyear." ".$thishour.":".$thisminute.":".$thissecond;
}else{
if(array_key_exists($key, $record)){
$sortedRow[$key] = $record[$key];
}else{
$sortedRow[$key] = '';
}
}
}
$rows[] = $sortedRow;
}
}
// Output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename='.$segments[2].'.csv');
// Create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// Output the column headings
fputcsv($output, $headers);
// Output the values
foreach ($rows as $row) {
fputcsv($output, array_values($row));
}
fclose($output);
exit;
}
Спасибо