CSV上传后将逗号分隔的字符串转换为两个字符串[PHP]
我有一个脚本,可以上传csv并将值分配给一个以逗号分隔的字符串CSV上传后将逗号分隔的字符串转换为两个字符串[PHP],php,string,csv,fgetcsv,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'){
$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.');
}
}
我的目标是
$city = "Munich, Berlin, London, Paris, Vienna, Milano, Rome";
$country = "Germany, Germany, UK, France, Austria, Italy, Italy";
我如何将$str分为国家和城市,或者可能应该在上传脚本中完成,我在上传脚本中循环搜索结果?您可以迭代数组
不要按照注释中的建议处理当前代码的结果,而是直接从CSV文件(仅包括相关部分)处理数据
从CSV检索时,为什么不将这两个信息保存在不同的对象中?我没有把它添加到一个字符串中,而是尝试了一下,但不知何故没有成功。你知道怎么做吗?在这里你可以得到答案
$city = "Munich, Berlin, London, Paris, Vienna, Milano, Rome";
$country = "Germany, Germany, UK, France, Austria, Italy, Italy";
$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);
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));
}