duancheng7743 2014-01-09 17:37
浏览 34
已采纳

php数组到CSV

I have an array of arrays

$numbers= array(3) {
  [months]=>
    array(3) {
      ["1"]=>
      string(7) "Jan"
      ["2"]=>
      string(7) "Feb"
     ["3"]=>
     string(7) "Mar"
  }
[dates]=>
  array(3) {
    ["1"]=>
    string(7) "12th"
    ["2"]=>
    string(7) "19th"
    ["3"]=>
    string(7) "22nd"
 }
  [people]=>
  array(3) {
    ["1"]=>
    string(7) "Bill"
    ["2"]=>
    string(7) "Ted"
    ["3"]=>
    string(7) "Gary"
 }
 }

I want to write the contents of these arrays into a CSV file in the form of a table so I get an output like:

 months,  dates, people 
 Jan,     12th,   Bill
 Feb,     19th,   Ted
 Mar,     22nd,   Gary

I want to try and put it directly from the array into the CSV in one move it it's possible but I can't find a way to do it without cutting it up.

  • 写回答

2条回答 默认 最新

  • dora1989 2014-01-09 17:55
    关注
    <?php
    // transform the array
    $keys = array_keys($numbers);
    array_unshift($numbers, null);
    $output = call_user_func_array('array_map', $numbers);
    array_unshift($output, $keys);
    
    // from php.net
    $fp = fopen('file.csv', 'w');
    
    foreach ($output as $fields) {
        fputcsv($fp, $fields);
    }
    
    fclose($fp);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?