PHP 和csv:一些对列的操作
我的 csv 看起来像这样:
column1_row1;column2_row1;column3_row1;column4_row1;... column15_row1
column1_row2;column2_row2;column3_row2;column4_row2;... column15_row2
column1_row3;column2_row3;column3_row3;column4_row3;... column15_row3
现在,对于每一行,我必须找到:
- 仅当第 12 列包含“word”时
- ,如果第 10 列值大于等于第 8 列值的 5%
在第一行:
- 在数据库表“alpha”中查找对于第 4 列中包含的相应参考编号,
- 将具有某些属性(例如正确的 id_number 和相对 %,格式为 0,230000 表示 23%)的一些数据(行)插入表“beta”(基于另一个表)列 id)
插入、更新并最终删除: 不仅执行相同的过程,还检查并注册百分比变化,如果不再验证变化(>=5%),则删除带有 id_number 的相应行。
编辑:
我发现了这样的内容:
$file_handle = fopen("filename.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
print $line_of_text[0];
}
fclose($file_handle);
但是如果它遇到逗号,它会被截断,我必须避免,然后必须访问列值,我不需要整行,也不需要什么大小1024 如果 csv 包含许多长文本描述,您是否建议?
My csv looks like this:
column1_row1;column2_row1;column3_row1;column4_row1;... column15_row1
column1_row2;column2_row2;column3_row2;column4_row2;... column15_row2
column1_row3;column2_row3;column3_row3;column4_row3;... column15_row3
Now for every row I have to find:
- Where column 12 contains "word" only
- IF column 10 value is >=5% of column 8 value
On the first line:
- Look in a database table "alpha" for the corresponding reference number contained in column 4,
- Insert some data (rows) with certain attributes (like the correct id_number and relative % in format 0,230000 for 23%) into table "beta" (based on another column id)
Insert, update and eventually remove:
Not only do the same procedure but also check and register percentage variations and delete the corresponding row with id_number if the variation (>=5%) is not verified anymore.
edit:
I found something like this:
$file_handle = fopen("filename.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
print $line_of_text[0];
}
fclose($file_handle);
But if it meets a comma it truncates and I have to avoid, then have to access the column values, I don't need the whole line, and what size instead of 1024 do you suggest if the csv contains many long text descriptions?
您的示例 csv 以分号分隔(而不是逗号),因此您需要将 fgetcsv 更改为:
From the PHP Manual for fgetcsv:
这将使您的行看起来像:
即使您可能不需要文件中的整行,您仍然会得到它,因为这就是 fgetcsv 的工作方式。
该数组的索引为零,因此您的 column1 将位于位置 0。
一旦您有了该行,您就可以使用您需要的字段,例如:
Your example csv is semicolon delimited (instead of comma) so you'll need to change your fgetcsv to:
From the PHP Manual for fgetcsv:
That will make your line look like:
Even though you may not need the whole line from the file, you are still going to get it, because that is the way fgetcsv works.
This array is zero indexed, so your column1 will be in position 0.
Once you have the line you can use the fields you need such as: