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

问题描述 投票:0回答:1

我有一个脚本,可以上传一个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分成国家和城市,或者应该在我遍历结果的上传脚本中完成?

php string csv fgetcsv
1个回答
1
投票
$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);
© www.soinside.com 2019 - 2024. All rights reserved.