【问题标题】:Convert comma separated string into two strings after CSV upload [PHP]CSV上传后将逗号分隔的字符串转换为两个字符串[PHP]
【发布时间】:2019-10-24 06:04:09
【问题描述】:

我有一个脚本可以上传 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 列城市和国家

我还将删除带有标题的第一行。所以在 $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 分成国家和城市,或者应该在我循环遍历结果的上传脚本中完成?

【问题讨论】:

  • 为什么在从 CSV 检索时没有将这两个信息保存在不同的对象中?而不是将其附加到字符串中。
  • 我尝试过,但不知何故没有成功。知道怎么做吗?
  • 在这里你可以得到答案stackoverflow.com/questions/2805427/…

标签: php string csv fgetcsv


【解决方案1】:

你可以迭代数组,Demo

$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);

【讨论】:

    【解决方案2】:

    不要处理当前代码的结果,而是按照评论中的建议,直接处理 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));
    }
    

    【讨论】:

      猜你喜欢
      • 2018-02-22
      • 2019-11-18
      • 2017-12-24
      • 1970-01-01
      • 2016-08-19
      • 2020-11-27
      • 2018-08-16
      • 2013-09-30
      • 1970-01-01
      相关资源
      最近更新 更多