在php中从行信息传递到两个数组

在php中从行信息传递到两个数组

问题描述:

I am beginner in php . In my application i have to read a csv file and store the values of each row in two variables: $name and latin.

 while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

                foreach($data as $value)
                {
                        if($i>8){
                        // $fgmembersite->InsertUserBirds($value);
                        echo $value;
                        }

                    }
                     $i++;
                  echo '<br/>' ;

               } fclose($handle);

each row row contains four or three words ( $name is the first and the second word (if the length of row is 4 words) and the $latin store the last two words: page

How can i do it to add the array $latin and $name ?

Seems this one is going to do exactly what you need:

$name = $latin = array();
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
    if (count($data) === 4) {
        $name[] = $data[0];
        $name[] = $data[1];
        $latin[] = $data[2];
        $latin[] = $data[3];
    } elseif ($count($data) === 3) {
        $name[] = $data[0];
        $latin[] = $data[1];
        $latin[] = $data[2];
    }
}

The best way to handle this data is to look for a more reliable source!

If you have to use this file, try the following:

  1. Use fgets to handle the file line by line.
  2. All species names are lower cased and all Genus names are capitalised so you could search for the rightmost capital letter. Everything from that point on is Latin, everything to the left is Common.

A more elegant approach is to use preg_match to find the last capital letter. I'm not good at regexp so hopefully an improvement can be made on mine, but the below will return your latin name as the last index of the array 'matches'. If you have got this far, you should be able to figure the rest out.

$matches=array();
$pattern="/([A-Z][a-z ]*)*/";
$testdata="Scabies Mite Sarcoptes scabii";
preg_match($pattern,$testdata,$matches);
var_dump($matches);

Although it can seem daunting learning regexp at the same time as PHP, even a little effort will be well rewarded and there are many helpful members on this site.