douwen7475 2014-05-07 20:20
浏览 43
已采纳

PHP将复杂订单信息写入CSV

I am writing an order exporter in PHP and am having difficulty with php checking a csv header and then writing to a file.

I have my code which opens the file, then writes to the csv

$fh = fopen($file_compile, 'w');

I then write my header:

$header = '"OrderId", "Customer";

foreach ($products as $product) {
  $header .= ', "' . $product . '"';
}

fputs($fh, $header . "
");

which gives me an output

enter image description here

I now generate my $line array

which outputs:

array(3) {
  ["OrderId"]=>
  string(9) "100000033"
  ["Customer"]=>
  string(14) "Graeme Houston"
  ["total"]=>
  array(3) {
    ["Socks"]=>
    int(12)
    ["Books"]=>
    int(23)
    ["Wallets"]=>
    int(12)
  }
}

Now as you can see, my array doesn't exactly match the CSV above it, which is fine, what I would like to achieve is, if there is a value in the total that matches a value in the header, to but the integer value in the cell. (scratches head)

To illustrate:

enter image description here

I must add I have been trying to figure this out for a few days, I cant get my head round it, hence the post on here. I would be extremely grateful if someone could point me in the right direction.

  • 写回答

1条回答 默认 最新

  • doute3621 2014-05-07 21:51
    关注

    Not that complex...

    $header = array('OrderId','Customer');
    
    foreach ($products as $product) {
      $header[] = $product;
    }
    
    $tmp = '"' .implode('","',$header) . '"';
    
    fputs($fh, $tmp . "
    ");
    

    For your header construction... Then for you line output something similar to:

    foreach($header as $key){
        if(empty($line[$key])) $line[$key] = NULL;
    
        if(empty($line[$key]) && !empty($line['total'][$key])){
             $line[$key] = $line['total'][$key];
        }
    }
    unset($line['total']);
    

    Now you've filled the gaps for non-existent columns, and given values to the existent ones.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突