使用php str_getcsv函数将csv文件数据转换为数组 [英] Converting csv files data to an array using php str_getcsv function
问题描述
我有使用 fputcsv
Date,Name,Hours 2013-01-02,"Test User",7:59 2013-01-03,"Test User",7:53 2013-01-04,"Test User",8:12 2013-01-07,"Test User",7:56 2013-01-08,"Test User",8:25 2013-01-09,"Test User",7:56 2013-01-10,"Test User",8:10 2013-01-11,"Test User",7:53 2013-01-14,"Test User",7:54 2013-01-15,"Test User",0:34 2013-04-01,"Test User",5:51 2013-04-02,"Test User",8:50 2013-04-03,"Test User",7:25 2013-04-04,"Test User",8:3 2013-04-05,"Test User","10:42:52[Not punch out]" ,Total,103:1
设置正确的标头(header('Content-type:application/csv'); header('Content-Disposition:Attachment; filename ='.$ filename.'"');)时,它会提供正确的csv文件
when proper header (header('Content-type: application/csv'); header('Content-Disposition: attachment; filename="'.$filename.'"');) is set it gives correct csv file.
但是我希望再次将此字符串转换为数组格式,因此我尝试将上述字符串传递给 str_getcsv ,但是得到这样的数组
But I want this string again to be converted to a array format so I tried passing above string to str_getcsv but getting array like this
Array
(
[0] => Date
[1] => Name
[2] => Hours
2013-01-02
[3] => "Allen Herrera"
[4] => 7:59
2013-01-03
[5] => "Allen Herrera"
[6] => 7:53
2013-01-04
[7] => "Allen Herrera"
[8] => 8:12
2013-01-07
[9] => "Allen Herrera"
[10] => 7:56
2013-01-08
[11] => "Allen Herrera"
[12] => 8:25
2013-01-09
[13] => "Allen Herrera"
[14] => 7:56
2013-01-10
[15] => "Allen Herrera"
[16] => 8:10
2013-01-11
[17] => "Allen Herrera"
[18] => 7:53
2013-01-14......................
能否帮助我获取格式正确的数组,以便我可以轻松地使用它在数组上创建表循环.
Can you help me to get properly formatted array so that I can easily use it to create table looping on the array.
推荐答案
稍作搜索后就找到了解决办法
After little searching got solution on this
$data = array_map("str_getcsv", preg_split('/\r*\n+|\r+/', $string_data));
print_r($data);
像这样给我数组
Array
(
[0] => Array
(
[0] => Date
[1] => Name
[2] => Hours
)
[1] => Array
(
[0] => 2013-01-02
[1] => Test User
[2] => 7:59
)
[2] => Array
(
[0] => 2013-01-03
[1] => Test User
[2] => 7:53
)
[3] => Array
(
[0] => 2013-01-04
[1] => Test User
[2] => 8:12
)
[4] => Array
(
[0] => 2013-01-07
[1] => Test User
[2] => 7:56
)
[5] => Array
(
[0] => 2013-01-08
[1] => Test User
[2] => 8:25
)
[6] => Array
(
[0] => 2013-01-09
[1] => Test User
[2] => 7:56
)
[7] => Array
(
[0] => 2013-01-10
[1] => Test User
[2] => 8:10
)...
这篇关于使用php str_getcsv函数将csv文件数据转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!