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

问题描述

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

代码,城市阿比林,德克萨斯州",ABI"阿达克岛, AK ",ADK"Akiachak, AK ",KKI"Akiak, AK ",AKI阿克伦/坎顿,哦",CAK阿库顿,AK",KQA"Alakanuk, AK ",AUK"阿拉莫戈多,新墨西哥州",ALM

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

if(($handle = fopen('test.csv', 'r')) !== FALSE) {while (($data = fgetcsv($handle, 1000, ',', '"')) !== FALSE) {echo '

';打印_r($数据);echo '</pre>';}fclose($handle);}

虽然我为 fgetcsv 函数设置了分隔符和包围字符,但我还是得到了这个结果:

数组([0] =>代码[1] =>城市阿比林[2] =>发送[3] =>ABI阿达克岛[4] =>啊"[5] =>广告开发工具包阿基恰克[6] =>啊"[7] =>KKI阿基亚克[8] =>啊"[9] =>AKI阿克伦/广州[10] =>哦 "[11] =>CAK阿库顿[12] =>啊"[13] =>昆山阿拉卡努克[14] =>啊"[15] =>澳大利亚联合王国阿拉莫戈多[16] =>NM"[17] =>ALM)
解决方案

如果是换行,可以试试暴力破解方法:

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

str_getcsv 在 PHP 5.3 中可用,或者作为手册中的解决方法,通过upgradephpPHP_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转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 02:32