将CSV转换为数组 [英] Converting CSV to array

查看:199
本文介绍了将CSV转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个机场代码和城市名称的数组(约3500行)。

 代码,城市
阿比林,TX,ABI
阿达克岛,AK,ADK
Akiachak,AK,KKI
Akiak,AK,AKI
Akron / OH,CAK
Akuton,AK,KQA
Alakanuk,AK,AUK
Alamogordo,NM,ALM
pre>

我需要将该文件转换为php数组。这是我的代码到目前为止:

  if(($ handle = fopen('test.csv','r')) !== FALSE){
while(($ data = fgetcsv($ handle,1000,',',''))!== FALSE){
echo'< pre>
print_r($ data);
echo'< / pre>';
}
fclose($ handle);
}

虽然我为fgetcsv函数设置了delimiter和enclousure字符,但我得到这个结果:

 数组

[0] => code
[1] => city
Abilene
[2] => TX
[3] => ABI
Adak Island
[4] =& ] => ADK
Akiachak
[6] => AK
[7] => KKI
Akiak
[8] =& AK
[9] => AKI
Akron / Canton
[10] => OH
[11] =&
[12] => AK
[13] => KQA
Alakanuk
[14] =& ; AUK
Alamogordo
[16] => NM
[17] => ALM


解决方案

如果是linebreaks,可以尝试使用brute-force方法:

  $ file = file_get_contents (test.csv); 
$ data = array_map(str_getcsv,preg_split('/ \r * \\\
+ | \r + /',$ file));
print_r $ data);

str_getcsv 适用于PHP 5.3,也可以通过 upgradedephp PHP_Compat


I have this array with airport codes and city names (around 3500 lines).

code,city
"Abilene, TX ",ABI
"Adak Island, AK ",ADK
"Akiachak, AK ",KKI
"Akiak, AK ",AKI
"Akron/Canton, OH ",CAK
"Akuton, AK ",KQA
"Alakanuk, AK ",AUK
"Alamogordo, NM ",ALM

I need to convert that file into a php array. This is my code so far:

if(($handle = fopen('test.csv', 'r')) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ',', '"')) !== FALSE) {
        echo '<pre>';
            print_r($data);
            echo '</pre>';
    }
    fclose($handle);
}

Although I'm setting the delimiter and enclousure characters for the fgetcsv function, im getting this as a result:

Array
(
    [0] => code
    [1] => city
"Abilene
    [2] => TX "
    [3] => ABI
"Adak Island
    [4] => AK "
    [5] => ADK
"Akiachak
    [6] => AK "
    [7] => KKI
"Akiak
    [8] => AK "
    [9] => AKI
"Akron/Canton
    [10] => OH "
    [11] => CAK
"Akuton
    [12] => AK "
    [13] => KQA
"Alakanuk
    [14] => AK "
    [15] => AUK
"Alamogordo
    [16] => NM "
    [17] => ALM
)

解决方案

If it's the linebreaks, you can try the brute-force method with:

$file = file_get_contents("test.csv");
$data = array_map("str_getcsv", preg_split('/\r*\n+|\r+/', $file));
print_r($data);

str_getcsv is available with PHP 5.3, or as workaround in the manual, via upgradephp or PHP_Compat.

这篇关于将CSV转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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