Tuesday 9 March 2010

array_combine

This nigh on killed me except I solved it last night while I was asleep. Now to turn it into a loop!

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>CSV12</title>
    </head>
    <body>
        <?php
          // file names.csv:
          /*
Name,Email Address,Phone Number
Bob Smith,bob@smith.com,01234567890
Martha Jones,martha@jones.com,0987643210
Joe Bloggs,joe.bloggs@gmail.com,01484522869
           */
          // get the file into an array
          $file = "names.csv";
          $fileHandle = fopen("names.csv", "r");
          // check that the array is a csv file
          if (substr(strrchr($file, '.'), 1) == "csv") {
            // count the number of lines in the file
            $lines = count(file($file));
            // display the result of the count
            echo "<p>There are $lines lines in $file</p>";
            // if there are more than 2 continue
            if ($lines > 1){
              // this is the first line as an array, we'll be using this as the
              // key to our key value array
              $firstLine = fgetcsv($fileHandle);
              // print the 1st line
              print_r($firstLine);
              // this is the second line, we'll be using this as the value to
              // out key value array
              $secondLine = fgetcsv($fileHandle);
              // print the 2nd line
              print_r($secondLine);
              // use array_combine to use values from the 1st line as keys and
              // values form out 2nd line as values to out key value array
              $firstSecond = array_combine($firstLine, $secondLine);
              // print it all out nice to check
              print_r($firstSecond);
              /*
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>CSV12</title>
    </head>
    <body>
        <p>There are 4 lines in names.csv</p>Array
(
    [0] => Name
    [1] => Email Address
    [2] => Phone Number
)
Array
(
    [0] => Bob Smith
    [1] => bob@smith.com
    [2] => 01234567890
)
Array
(
    [Name] => Bob Smith
    [Email Address] => bob@smith.com
    [Phone Number] => 01234567890
)
    </body>
</html>            
                */
            }
            // if less than 2 it's not a valid file
            else {
              echo "There are not enough lines to work with.";
            }
          }
        ?>
    </body>
</html>

No comments:

Post a Comment