reading a file

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Christian Christmann

    #1

    reading a file

    Hi,

    I have a file which has a bunch of entries (student's data). Its structure
    looks like

    Number1|ID|name |surname|emaila ddress

    As can be seen, the entries are seperated by a "|".

    Now I would like to create 5 arrays where I store all the entries
    seperatly, for instance an array for the ID, one for the name ....

    How do I read out the file and save the data to the arrays?

    Thanks

    Christian
  • Daniel Tryba

    #2
    Re: reading a file

    Christian Christmann <plfriko@yahoo. de> wrote:[color=blue]
    > I have a file which has a bunch of entries (student's data). Its structure
    > looks like[/color]

    Homework?
    [color=blue]
    > Number1|ID|name |surname|emaila ddress
    >
    > As can be seen, the entries are seperated by a "|".
    >
    > Now I would like to create 5 arrays where I store all the entries
    > seperatly, for instance an array for the ID, one for the name ....
    >
    > How do I read out the file and save the data to the arrays?[/color]

    Take a look at the filesystem functions:


    A simple (but surely not the most memory efficient way)

    -file() to read the datafile in an array
    -for(each) to loop through the entries
    -explode to seperate the entries per line
    -add those (for(each) loop) to your per type arrays

    fopen/fgetcsv would be more efficient.

    --

    Daniel Tryba

    Comment

    • Shawn Wilson

      #3
      Re: reading a file

      Christian Christmann wrote:[color=blue]
      >
      > I have a file which has a bunch of entries (student's data). Its structure
      > looks like
      >
      > Number1|ID|name |surname|emaila ddress
      >
      > As can be seen, the entries are seperated by a "|".
      >
      > Now I would like to create 5 arrays where I store all the entries
      > seperatly, for instance an array for the ID, one for the name ....
      >
      > How do I read out the file and save the data to the arrays?[/color]

      This should work (UNTESTED):
      $num = array();
      $id = array();
      $name = array();
      $surname = array();
      $email = array();

      $arr = file('path/to/file');
      $arrcount = count($arr);

      foreach($arr as $val)
      list($num[], $id[], $name[], $surname[], $email[]) = split('|', $val);


      This is a bit shorter but doesn't give you 5 seperate arrays (UNTESTED):

      $newarray = array();

      $arr = file('path/to/file');

      foreach($arr as $val)
      $newarray[] = split('|', $arr);


      I will leave the error checking up to you...

      Shawn

      --
      Shawn Wilson
      shawn@glassgian t.com

      Comment

      Working...