【问题标题】:PHP fputcsv different columnsPHP fputcsv不同的列
【发布时间】:2020-07-09 09:46:38
【问题描述】:

我正在将数据导出到 csv 我有多个要添加到 csv 文件的数组。我能够将数据插入到第一个数组的 csv 中。

我想要将第二个数组数据与第一个数组数据平行放置。

示例 csv:

Array1:               Array2:       Array3:
1 2 3 4               a b c d       xd xy cd
5 6 7 8               e f g h       dg dy cs

代码:

$output = fopen('php://output', 'w+');


  foreach ($ofdPerCompany as $row){

    $array = array( $row->company_name, $row->countofwaybill);
    fputcsv($output, $array); // here you can change delimiter/enclosure
}

    // tell the browser it's going to be a csv file
    header('Content-Type: application/csv');
    // tell the browser we want to save it instead of displaying it
    header('Content-Disposition: attachment; filename="file.csv";');

  fclose($output);

谁能帮助我如何将 csv 拆分为不同的列。

【问题讨论】:

  • 你试过array_merge()吗?
  • 我有不同的记录数的单独数组。

标签: php csv export-to-csv fputcsv


【解决方案1】:

如果您有三个包含不同数量记录的数组,您可以执行以下操作:

$first = [];
$second = [];
$third = [];

// Get maximum size
$maxLength = max(count($first), count($second), count($third));

// Write headers manually
fputcsv($fh, ["First", "Second", "Third"]);

for ($i = 0; $i < $maxLength; $i++) {
  // If key does not exist use empty string
  $data = [
    $first[$i] ?? "",
    $second[$i] ?? "",
    $third[$i] ?? ""
  ];

  fputcsv($fh, $data);
}

【讨论】:

  • 谢谢,我会试一试的。
猜你喜欢
  • 1970-01-01
  • 2012-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多