#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    1
    Rep Power
    0

    Get keyfield from one csv file and search for it in another csv file and output


    file1.csv:

    0|john smith|london|23
    1|david adams|bath|35
    2|sean white|liverpool|61


    file2.csv:

    1|boat|car|train
    0|scooter|moped|aircraft|
    2|walk|cycle|run

    I want to use php. The first number in both files is the key field. I want to open the first file, and go through all the keyfields one by one. If the keyfield in the first file matches the keyfield in the second file, then output the data from the same row in the second file.

    output will be :

    john uses a scooter, moped and aircraft sean walks, cycles and runs and david uses boat, car and train

    Thanks for your help on this, I'm losing sleep...!
  2. #2
  3. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    13,997
    Rep Power
    9397
    fopen, fgetcsv, fclose

    First get everything in file2 into an array.
    PHP Code:
    $file2 = array();
    // for each $line, which is an array returned by fgetcsv(), in file2.csv {
        
    $key array_shift($line);
        
    $file2[$key] = $line;
    // } 
    Then you can use $file2[0] to get an array of everything "john smith" uses.

    After that, use another loop to read from file1. If the appropriate item isset() in $file2 then display it, otherwise do something else (eg, "doesn't use anything").

    Give that a shot. If you have trouble getting it to work, post your code here and describe the problem.

    Comments on this post

    • ManiacDan agrees : FINE
  4. #3
  5. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,853
    Rep Power
    6351
    use fopen and fgetcsv to parse file2 first, into an array keyed by the first field. Close the file.

    Then use the same technique to loop through the first file, checking its first field against the keys in the array you made from file2. Output if necessary.

    Comments on this post

    • requinix agrees : three minutes
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.

IMN logo majestic logo threadwatch logo seochat tools logo