CSV上传后,将逗号分隔的字符串转换为两个字符串[PHP]

时间:2019-10-24 06:04:09

标签: php string csv fgetcsv

我有一个脚本,可以上传一个csv并将值分配给以逗号分隔的字符串

$has_title_row = true;
if( $_POST['upload_file'] == 1 ) {
    if(is_uploaded_file($_FILES['csvfile']['tmp_name'])){
        $filename = basename($_FILES['csvfile']['name']);

        if(substr($filename, -3) == 'csv'){
            $tmpfile = $_FILES['csvfile']['tmp_name'];
            if (($fh = fopen($tmpfile, "r")) !== FALSE) {
                $i = 0;
                while (($items = fgetcsv($fh, 10000, ",")) !== FALSE) {
                    if($has_title_row === true && $i == 0){ // skip the first row if there is a tile row in CSV file
                        $i++;
                        continue;
                    }
                    //$data = print_r($items);
                    $i++;

                        $num = count($items);

                        $row++;
                        $str = '';
                        for ($c=0; $c < $num; $c++) {
                            //echo $items[$c] . ", ";
                            $str .= $items[$c] . ", ";
                        }
                } 
            }
        }
        else{
            die('Invalid file format uploaded. Please upload CSV.');
        }
    }
    else{
        die('Please upload a CSV file.');
    }
}

在我要上传的csv中,我有2列城市和国家/地区

enter image description here

我还要删除标题的第一行。所以在$ str中我有类似的东西

$str = "Munich, Germany, Berlin, Germany, London, UK, Paris, France, Vienna, Austria, Milano, Italy, Rome, Italy";

我想要的结果是

$city = "Munich, Berlin, London, Paris, Vienna, Milano, Rome";
$country = "Germany, Germany, UK, France, Austria, Italy, Italy";

如何将$ str划分为国家和城市,或者应该在我遍历结果的上传脚本中完成?

2 个答案:

答案 0 :(得分:2)

您可以迭代数组documentation provided

$str = "Munich, Germany, Berlin, Germany, London, UK, Paris, France, Vienna, Austria, Milano, Italy, Rome, Italy";
$array = explode(",",$str);
foreach($array as $k => $value){
    if($k % 2){
        $country_list[] = $value;
    }else{
        $city_list[] = $value;
    }
}
$city = join(",",$city_list);
$country = join(",",$country_list);

答案 1 :(得分:1)

遵循注释中的建议,而不是处理当前代码的结果,而是直接从CSV文件(仅包括相关部分)中处理数据...

if (($fh = fopen($tmpfile, "r")) !== FALSE) {
    // Skip header
    $header = fgetcsv($fh);
    $cities = [];
    $countries = [];
    while (($items = fgetcsv($fh)) !== FALSE) {
        $cities[] = $items[0];
        $countries[] = $items[1];
    }

    print_r(implode(",",$cities));
    print_r(implode(",",$countries));
}
相关问题