我们有一个基于PHP的网站,该网站根据精选的Markdown文件生成CSV导出。我们可以选择一个月的文件并以这种方式导出。
我们试图实现的目标是通过以下方式制作CSV标头:
一些简单的Markdown文件示例
文件1:
b: 'value'
c: 'value'
d: 'value'
文件2:
a: 'value'
b: 'value'
d: 'value'
文件3:
a: 'value'
c: 'value'
d: 'value'
将这些导出为CSV文件,我希望标题为 一个| b | 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;
}
谢谢
答案 0 :(得分:0)
一旦将字母排列在数组中,就可以对数字和数字使用min
和max
函数。同样是比较和递增!
<?php
$letters = str_split("abdh");
$min = min($letters);
$max = max($letters);
for ($i = $min; $i <= $max; $i++) {
echo $i;
}
输出:
abcdefgh
(确定这是纯粹的荒谬,还是出色的PHP功能留给读者练习。)