在PHP中导出带有匹配头的CSV

polkgigr  于 2023-04-09  发布在  PHP
关注(0)|答案(1)|浏览(149)

我想导出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')
);

**有关所需输出,请参见屏幕截图:**x1c 0d1x

cl25kdpy

cl25kdpy1#

下面是一个可能的实现:

// $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);

相关问题