在 PHP 中导出带有匹配标题的 CSV

问题描述 投票:0回答:1

我想导出带有匹配标题的 CSV。请在下面检查我的数据并查看我真正想要的输出。我试过但找不到合适的解决方案。谁能帮忙!!!

标题数据,

$headers = array('name', 'sku', 'short_description', 'brand', 'website', 'price', 'url_key', 'weight', 'length');

数组数据:

$data = array(
array('name'=>'Name 1', 'brand'=>'Brand 1', 'url_key'=>'URL key 1', 'length'=>'length 1'),
array('name'=>'Name 2', 'short_description'=>'Shord Description 2', 'sku'=>'SKU 2', 'price'=>'Price2'),
array('name'=>'Name 3', 'sku'=>'SKU 3', 'website'=>'Website 3', 'price'=>'Price 3', 'url_key'=>'URL KEY 3', 'length'=>'Lenght 3'),
array('sku'=>'SKU 4', 'short_description'=>'Short Des 4', 'website'=>'Website 4', 'price'=>'Price4', 'url_key'=>'URL KEY 4')
);

所需输出请看截图:

php csv export-to-csv fputcsv
1个回答
1
投票

这里是一个可能的实现:

// $csvData will be the array that contains the data for our final CSV
$csvData = [ $headers ]; // adding the headers on the first row

foreach ($data as $row) {
    $csvRow = [];
    foreach ($headers as $header) {
        // checking if the row in the $data array has the value corresponding to the header, if it does not it adds an empty string
        $csvRow[$header] = isset($row[$header]) ? $row[$header] : '';
    }
    $csvData[] = $csvRow;
}

// creating the CSV
$outputFile = fopen('output.csv', 'w');
foreach ($csvData as $csvDataRow) {
    fputcsv($outputFile, $csvDataRow);
}
fclose($outputFile);
© www.soinside.com 2019 - 2024. All rights reserved.