Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/vim/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何检索选项卡分隔列表中的第一列_Php_File Handling - Fatal编程技术网

Php 如何检索选项卡分隔列表中的第一列

Php 如何检索选项卡分隔列表中的第一列,php,file-handling,Php,File Handling,好了,伙计们,我有一个如下格式的列表: Entry-no.1[tab]Description[line-break] Entry-no.2[tab]Description[line-break] Entry-no.3[tab]Description[line-break] and so on... Entry-no.1,Entry-no.2,Entry-no.3,etc.. 我已尽一切努力隔离“条目列”,并创建一个逗号分隔的表格,如下所示: Entry-no.1[tab]Descriptio

好了,伙计们,我有一个如下格式的列表:

Entry-no.1[tab]Description[line-break]
Entry-no.2[tab]Description[line-break]
Entry-no.3[tab]Description[line-break]
and so on...
Entry-no.1,Entry-no.2,Entry-no.3,etc..
我已尽一切努力隔离“条目列”,并创建一个逗号分隔的表格,如下所示:

Entry-no.1[tab]Description[line-break]
Entry-no.2[tab]Description[line-break]
Entry-no.3[tab]Description[line-break]
and so on...
Entry-no.1,Entry-no.2,Entry-no.3,etc..
下面是我能想到的最好的代码,但它不起作用:(




另外,我无法更改文件的原始布局。

这应该可以做到这一点。文档应保持一致

// read file into array
$array = file('File.txt');

// new array to store results
$new_array = array();

// loop through array
foreach ($array as $line) {
    // explode the line on tab. Note double quotes around \t are mandatory
    $line_array = explode("\t", $line);
    // set first element to the new array
    $new_array[] = $line_array[0];
}

// you can either use this array as is or output as comma-separate value as follows:
echo implode(',', $new_array);
总而言之:

  • 将文件读入数组而不是字符串。这将为您处理换行
  • 在制表符之前获取每行的一部分,并放入新数组中
  • 务必在
    \t
    周围使用双引号,否则它将被视为文字反斜杠和t

@snocavtoia,换行符将由str_getcsv函数处理……这就是它知道它是记录的结尾的方式。接受这个天真的实现。数字。我不知道为什么我还要再费事贡献这么多。真是个笑话。非常感谢!完美无缺!最好不要在以制表符分隔的CSV文件中添加新列。@crush This approv只要他感兴趣的信息仍然位于第一列或已知列偏移量(即X而不是0),ach仍然是合适的。但是,通过使用字符串提取而不是分解来获取第一个元素,他可能会占用更少的内存。在这种情况下,为了解释清楚,我确实分解了。