[英]How to filter on a word in a specific column of a csv file with PHP
I'm trying to display only the rows that contain a specific word in a specific column. 我正在尝试仅显示特定列中包含特定单词的行。 Basically I would like to show only the rows that have "yes" in the Display column. 基本上,我只想显示“显示”列中具有“是”的行。
First_Name, Last_Name, Display
Kevin, Smith, yes
Jack, White, yes
Joe, Schmo, no
I've been trying various things with fgetcsv & str_getcsv from other answers and from php.net but nothing is working so far. 我一直在尝试从其他答案和php.net用fgetcsv和str_getcsv进行各种操作,但到目前为止没有任何效果。
It doesn't do anything but this is my current code: 它什么也没做,但这是我当前的代码:
$csv = fopen('file.csv', 'r');
$array = fgetcsv($csv);
foreach ($array as $result) {
if ($array[2] == "yes") {
print ($result);
}
}
Let's have a look at the documentation for fgetcsv()
: 让我们看一下fgetcsv()
的文档 :
Gets line from file pointer and parse for CSV fields 从文件指针获取行并解析CSV字段
fgetcsv
reads a single line , not the whole file. fgetcsv
读取一行 ,而不读取整个文件。 You can keep reading lines until you reach the end of the file by putting it in a while
loop, eg 您可以通过将其置于while
循环中来不断读取行,直到到达文件末尾,例如
<?php
$csv = fopen('file.csv', 'r');
// Keep looping as long as we get a new $row
while ($row = fgetcsv($csv)) {
if ($row[2] == "yes") {
// We can't just echo $row because it's an array
//
// Instead, let's join the fields with a comma
echo implode(',', $row);
echo "\n";
}
}
// Don't forget to close the file!
fclose($csv);
You should use data tables. 您应该使用数据表。 https://datatables.net/examples/basic_init/zero_configuration.html https://datatables.net/examples/basic_init/zero_configuration.html
That's how I deal with my textfiles. 这就是我处理文本文件的方式。 But be carefull, with a large amount of Data (> 10000 rows) you should have a loog at the deferRender option. 但是要小心,在有大量数据(> 10000行)的情况下,您应该对deferRender选项感到困惑。 https://datatables.net/reference/option/deferRender <-- JSON DATA required. https://datatables.net/reference/option/deferRender <-需要JSON数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.