You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过CSV将数组值转置实现行转列输出(含PHP代码)

How to Transpose Rows to Columns in Your PHP-Generated CSV

Got it, let's fix this so your CSV downloads with columns turned into rows (and vice versa). The key here is to first collect all your data (including headers) into an array, transpose that array, then write it out to the CSV. Here's how to modify your existing code:

Modified Full Code

<?php
// Output headers to trigger file download instead of display
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="transposed_csv.csv"');
header('Pragma: no-cache');
header('Expires: 0');

// Create a file pointer connected to the output stream
$file = fopen('php://output', 'w');

// Step 1: Collect ALL data (headers + rows) into a single array
$data = [
    ['Filepath', 'Folders', 'Date'] // Your original column headers
];

// Replace this section with your actual RecursiveIterator logic to fetch data
$shopurl = "https://www.example.com/";
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('/your/target/directory'));
foreach ($iterator as $fileInfo) {
    if (!$fileInfo->isFile()) continue; // Skip directories
    
    // Populate your data rows (adjust these values to match your actual dataset)
    $filepath = $fileInfo->getPathname();
    $folders = $fileInfo->getPath();
    $date = date('Y-m-d H:i:s', $fileInfo->getMTime());
    
    $data[] = [$filepath, $folders, $date];
}

// Step 2: Transpose the array (turn rows into columns)
// This uses a PHP trick to flip the structure of the 2D array
$transposedData = array_map(null, ...$data);

// Step 3: Write the transposed data to the CSV
foreach ($transposedData as $row) {
    fputcsv($file, $row);
}

fclose($file);
exit;
?>

Key Details to Note:

  • Data Collection: Instead of writing rows directly to the CSV as you iterate, we first store everything in the $data array. This lets us manipulate the entire dataset before output.
  • Array Transposition: The line array_map(null, ...$data) is a clean way to transpose a 2D array in PHP. It takes each column from your original data and converts it into a row in the new array. If some rows are shorter than others, it fills missing values with null—which fputcsv automatically converts to empty CSV cells for consistent formatting.
  • Final Output: We loop through the transposed array and write each new row (originally a column in your data) to the output stream, resulting in the column-based CSV you need.

内容的提问来源于stack exchange,提问作者Rob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:32:17