While Loop and Arrays

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kardon33
    New Member
    • May 2007
    • 158

    While Loop and Arrays

    Ok ill explain what im doin. I have to convert a .csv file and output it into a mysql data base but before i do it i have to manipulate it a little. Im using this code to import the .csv file,

    Code:
    file = fopen("$filename", "r+"); #Reads the file names. 
    
         while (($data = fgetcsv($file, 1000, ",")) !== FALSE){}
    What i am trying to accomplish right after i get the data is put it into one multidimensiona l array.

    but how would i do this, i considered maybe creating an array and pushing each row i get in the while loop into it.

    Let me know if anyone has any ideas.
  • mwasif
    Recognized Expert Contributor
    • Jul 2006
    • 802

    #2
    [PHP]
    $file = fopen("$filenam e", "r+"); #Reads the file names.
    while (($data = fgetcsv($file, 1000, ",")) !== FALSE)
    {
    // here you have each row's data in array $data
    // $data[0] contains 1st column's data, $data[1] contains 2nd column's data and so on
    // here you can isert data into db or you can echo or manipulate it.
    }
    [/PHP]

    Comment

    • Purple
      Recognized Expert Contributor
      • May 2007
      • 404

      #3
      Hi kardon33,

      another way to do this using a multidimensiona l array would be to use file() which will read the whole file into an array for you and then explode to split the record into an array to allow you to process it

      Purple

      Comment

      • mwasif
        Recognized Expert Contributor
        • Jul 2006
        • 802

        #4
        Yes, you can use file() as purple suggested but i prefer to use fgetcsv() because it can handle quotes easily and effectively.

        Comment

        • pbmods
          Recognized Expert Expert
          • Apr 2007
          • 5821

          #5
          All you have to do is append your $data array onto your base array:

          [code=php]
          $theData = array();
          while (($data = fgetcsv($file, 1000, ",")) !== FALSE)
          $theData += $data;
          [/code]

          Comment

          Working...