用PHP搜索CSV [英] Searching a CSV With PHP

查看:90
本文介绍了用PHP搜索CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的CSV文件.第一列包含处理器的名称.第二,处理器的基准分数. EG:

I have a large CSV file. The first column contains the name of a processor. The second, the processor's benchmark score. EG:

Intel Pentium Dual T3400 @ 2.16GHz,1322

Intel Pentium Dual T3400 @ 2.16GHz,1322

使用PHP脚本,我想在第一列中搜索字符串(例如,EG.Pentium Dual T3400),并(假设每次搜索只有一个结果,否则返回错误消息)创建一个包含以下内容的变量:第二列的值.

Using a PHP script, I would like to search the first column for a string (EG. Pentium Dual T3400), and (assuming that there is only one result per search, else return an error message) create a variable containing the value of the second column.

我不知道这是否有帮助,但我有点希望它看起来像这样:

I don't know if this will help, but I was sort of hoping it would look a little like this:

$cpuscore = csvsearch(CSV_file,query_string,column#_to_search,column#_to_return)

$ cpuscore将包含与搜索查询匹配的处理器名称的分数.

Where $cpuscore would contain the score of the processor name that matches the search query.

请随意提出可能产生相似结果的建议.我有MySQL,但没有从CSV导入表的权限.

Feel free to suggest something that would produce similar results. I have MySQL, but I don't have the permissions to import tables from CSV.

推荐答案

您可以使用php函数fgetcsv(), http://php.net/manual/zh-CN/function.fgetcsv.php 逐行遍历csv文件.例如:

You can use the php function fgetcsv(), http://php.net/manual/en/function.fgetcsv.php to traverse the csv file row by row. For instance:

$ch = fopen($path_to_file, "r");
$found = '';

/* If your csv file's first row contains Column Description you can use this to remove the first row in the while */
$header_row = fgetcsv($ch);

/* This will loop through all the rows until it reaches the end */
while(($row = fgetcsv($ch)) !== FALSE) {

    /* $row is an array of columns from that row starting at 0 */
    $first_column = $row[0];

    /* Here you can do your search */
    /* If found $found = $row[1]; */
    /* Now $found will contain the 2nd column value (if found) */

}

这篇关于用PHP搜索CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆