0

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.

7
  • fputcsv() might help, but we're not going to write it for you. Personally, if the array is that small, I'd be inclined to use the SPL MultipleIterator to "transpose" the arrays Commented Jan 9, 2014 at 17:38
  • @MarkBaker He'd need to first transform his array. Commented Jan 9, 2014 at 17:40
  • Note: CSV stands for "Comma-separated values". if you're using CSV for a reason you might want to separate your values with commas OR just use a simple txt file Commented Jan 9, 2014 at 17:40
  • Since your arrays are the columns and the standard functions work by rows you probably need to work this manually through loops. Commented Jan 9, 2014 at 17:40
  • @MarkBaker the arrays aren't small the example is just to try and make sense of how I want the output to look rather than indicative of what it actually does. Commented Jan 9, 2014 at 17:59

2 Answers 2

1
<?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);
Sign up to request clarification or add additional context in comments.

Comments

1
$mi = new MultipleIterator();
$headers = array();
foreach($numbers as $header => $data) {
    $mi->attachIterator(new ArrayIterator($data));
    $headers[] = $header;
}

$fh = fopen('myfile.csv', 'w');
fputcsv($fh, $headers);
foreach($mi as $values) {
    fputcsv($fh, $values);
}
fclose($fh);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.