我有一个如下所示的CSV文件:
Main Road \t B \t 3
Main Road \t B \t 3
Main Road \t B \t 5
Example Road \t B \t 3
我需要像这样输出:
Main Road,B3-B5
Example Road, B3
我需要:
删除重复的行
将“主要道路”与“B”和“3”放在一起
检查两行是否有不同的名称,如果是:
到目前为止,我至少尝试将它们分成一个关联数组,其中街道名称是索引:
$postData = file_get_contents("php://input");
$separator = "\n";
$line = strtok($postData, $separator);
while ($line !== false) {
$line = strtok($separator);
$str = explode("\t",$line);
list($a, list($b, $c)) = array($str[0], array($str[0], $str[0]));
$arr[$str[0]] = $str[1].$str[2];
}
foreach ($arr as $key => $value) {
echo $key."=>".$value."<br>";
}
问题是部分有效:
Notice: Undefined offset: 1 in C:\xampp\htdocs\pietruska-crm\php\indexCSV.php on line 13
Notice: Undefined offset: 2 in C:\xampp\htdocs\pietruska-crm\php\indexCSV.php on line 13
Hambrücker Straße=>C3
Langestraße=>C2
Weiherer Straße=>E3
为什么偏移量未定义,但输出有效? 我怎么能有效地构建这个?关于如何创建列表数组,PHP列表的文档相当模糊。
由于
答案 0 :(得分:0)
试试这个:
$array_of_lines = explode('\n',$postData);
$array_of_lines = array_unique($array_of_lines); // delete duplicate strings
$handled_array_of_lines = array();
foreach ($array_of_lines as $line) {
$array_of_values = explode("\t",$line); // now you have array('Road',B,3)
$road = $array_of_values[0];
$param = $array_of_values[1].$array_of_values[2];
// check if the road meets first time or not; if not, add new param into this road entry
if (!isset($handled_array_of_lines[$road])) {
$handled_array_of_lines[$road] = $param;
} else {
$handled_array_of_lines[$road] .= '-'.$param;
}
}
foreach ($handled_array_of_lines as $road => $param) {
echo $road."=>".$param."<br>";
}