0

I have a php page that is creating a csv file for download which is made up of an array. Short version of Array:

$data = array("Joe Bloggs", "jbloggs", "John Doe", "jdoe")

My array is made from output from other commands so i cant just change the layout of my array, i can make two arrays, one for names and one for usernames if that help achieve my goal.

This is what i am doing to add the array values into my csv file:

$output = fopen('php://output', 'wb');
fputcsv($output, array('Name', 'Username'));
foreach ($data as $line ) {
    $val = explode(",", $line);
    for ($i=0; $i<$val["count"]; $i++); {

    fputcsv($output , array($val[$i])); 
    }
}

fclose($output);

This gives me a csv that looks like this:

Name      | Username
Joe Bloggs|
jbloggs   |
John Does |
jdoe      |

Really i need to have the usernames on the same row but in the username column. I have tried this and lots of variations on this but it does not seem to work, my thinking was i increase N by two each time so $i will be the name because it is every other index position and then when doing the fputcsv it would add 1 to $i so it would grab the username as it is the value after the name.

foreach ($data as $line ) {
    $val = explode(",", $line);
    for ($i=0; $i<$val["count"]; $i+=2); {

    fputcsv($output , array($val[$i], $val[$i+1])); 
    }
}

fclose($output);

Using the above gives me all the values in column one still.

Apologies for the write my code style question but i am out of my depth on this and cant find how to get to two consecutive values in a for loop of an array.

3
  • $val[i+1] - you meant $i there, not i. Commented Dec 3, 2019 at 10:57
  • I did thanks got rid of the error but still get all values in one collumn Commented Dec 3, 2019 at 10:59
  • Well how much “exploding by comma” do you expect to actually happen on a value like Joe Bloggs? That value looks pretty comma-less to me. Commented Dec 3, 2019 at 11:00

2 Answers 2

1

Here is 1 way of doing it.

$output = fopen('php://output', 'wb');
fputcsv($output, array('Name', 'Username'));

$temp = []; //Define a temp array.
foreach ($data as $line ) {
    $temp[]= $line;
    if( count( $temp) == 2 ) { //If no. of values in temp array is 2, write to csv file
        fputcsv($output , $temp );
        $temp = []; //initialize $temp;
    }
}

fclose($output);

Sign up to request clarification or add additional context in comments.

Comments

1

You can use simply these two line codes.

  for ($i=0 ;$i < count($data);$i+2) {       
     fputcsv($output , $data[$i],$data[$i+1]);          
  }

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.