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.
2
Answers
Here is 1 way of doing it.
You can use simply these two line codes.