PHP CSV VLookup

你离开我真会死。 提交于 2019-12-06 02:08:11

问题


I'm looking a PHP function that can read a CSV file and perform a vlookup on column 1 to echo the relating value on the same row in column 2.

For example, if the CSV contains:

Name,Email
John,john@domain1.com
Frank,frank@domain2.com
Julie,julie@domain3.com

I would like to lookup against a Name and echo the email value.

Something like:

<?php
$name = "Name to be inserted";
$csv = 'filename.csv';

*function to vlookup $name in $csv, get column 2 value and pipe to $email* 

echo $email;
?>

Can anyone suggest a function that can accomplish the above?

Thank you


回答1:


$csv = array_map('str_getcsv', file('test.csv'));
$findName="Frank";
foreach($csv as $values)
{
  if($values[0]==$findName)   // index 0 contains the name
    echo $values[1];          // index 1 contains the email  
}

Please note that the indexes used in this answer are specific to the csv format you gave. You will have to adjust the indexes if format changes.




回答2:


<?php

//Name,Email
//John,john@domain1.com
//Frank,frank@domain2.com
//Julie,julie@domain3.com

// Function Definition
function getEmailFromCSV($csv_name, $name) {
$file = fopen($csv_name, "r");

while (!feof($file)) {
    $arr = fgetcsv($file);
    if ($arr[0] == $name) {
        echo $arr[1];
    }
}
fclose($file);
}

// Function Calling
getEmailFromCSV('abc.csv', 'John');

// Input : John
// Output : john@domain1.com

?>


来源:https://stackoverflow.com/questions/30498765/php-csv-vlookup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!