skip to Main Content

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


  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);
    
    
    Login or Signup to reply.
  2. You can use simply these two line codes.

      for ($i=0 ;$i < count($data);$i+2) {       
         fputcsv($output , $data[$i],$data[$i+1]);          
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search