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 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算