我上传了一个csv文件,然后使用str_getcsv解析它.一切都很好,除了我需要一种方法来循环它们.理想情况下,让阵列回来看起来很棒:
Array ( [1] => Array ( [0] => 1 // first id in csv [1] => name [2] => address [3] => town [4] => state [5] => zip [6] => phone [7] => website [8] => other [9] => other ) [22] => Array ( [10] => name [11] => address [12] => town [13] => state [14] => zip [15] => phone [16] => website [17] => other [18] => other ) [24] => Array ( [19] => name [20] => address [21] => town [22] => state [23] => zip [24] => phone [25] => website [26] => other [27] => other ) )
但是,数据返回如下:
Array ( [0] => 1 // first id in csv [1] => name [2] => address [3] => town [4] => state [5] => zip [6] => phone [7] => website [8] => other [9] => other 22 // id field [10] => name [11] => address [12] => town [13] => state [14] => zip [15] => phone [16] => website [17] => other [18] => other 24// id field [19] => name [20] => address [21] => town [22] => state [23] => zip [24] => phone [25] => website [26] => other [27] => other
有关如何修复此问题的建议,看起来像顶部的数组?
现在我正在做:
$csvfile = file_get_contents($targetFile); $csv = str_getcsv($csvfile);
str_getcsv()期望作为参数传递的字符串是一条记录.
但是因为你的源文件无论如何最简单的方法是使用 fgetcsv()而不是str_getcsv()
原文链接:https://www.f2er.com/php/130742.html但是因为你的源文件无论如何最简单的方法是使用 fgetcsv()而不是str_getcsv()
$data = array(); $fp = fopen($targetFile,'rb'); while(!feof($fp)) { $data[] = fgetcsv($fp); } fclose($fp);
自包含的例子:
<?PHP $targetFile = 'soTest.csv'; setup($targetFile); $data = array(); $fp = fopen($targetFile,'rb'); while(!feof($fp)) { $data[] = fgetcsv($fp); } var_dump($data); function setup($targetFile) { file_put_contents($targetFile,<<< eot 1,name,address,town,state,zip,phone,website,other,other 2,other 3,other eot ); }
版画
array(3) { [0]=> array(10) { [0]=> string(1) "1" [1]=> string(4) "name" [2]=> string(7) "address" [3]=> string(4) "town" [4]=> string(5) "state" [5]=> string(3) "zip" [6]=> string(5) "phone" [7]=> string(7) "website" [8]=> string(5) "other" [9]=> string(5) "other" } [1]=> array(10) { [0]=> string(1) "2" [1]=> string(4) "name" [2]=> string(7) "address" [3]=> string(4) "town" [4]=> string(5) "state" [5]=> string(3) "zip" [6]=> string(5) "phone" [7]=> string(7) "website" [8]=> string(5) "other" [9]=> string(5) "other" } [2]=> array(10) { [0]=> string(1) "3" [1]=> string(4) "name" [2]=> string(7) "address" [3]=> string(4) "town" [4]=> string(5) "state" [5]=> string(3) "zip" [6]=> string(5) "phone" [7]=> string(7) "website" [8]=> string(5) "other" [9]=> string(5) "other" } }
edit2:使用每个记录的第一个元素作为结果数组中的键:
<?PHP $targetFile = 'soTest.csv'; setup($targetFile); $data = array(); $fp = fopen($targetFile,'rb'); while(!feof($fp)) { $row = fgetcsv($fp); $id = array_shift($row); $data[$id] = $row; } var_dump($data); function setup($targetFile) { file_put_contents($targetFile,other eot ); }