PHP tab delimited text file into array

不打扰是莪最后的温柔 提交于 2019-12-10 15:53:06

问题


I have a huge text file structured like so:

email 1
email 14
email 1
email 244
email 232
email 23
email 1

I'm trying to pull the text file into an array, where I can then remove all emails that so not have a number one. Right now I'm limiting to the first 20, all of which have the number 1, but the only thing I'm getting in my array is the number 1. When I spit out the number of items in the line it says 1.

$file = "list.txt";// Your Temp Uploaded file
$cols = array();
ini_set('auto_detect_line_endings', true);

$fh = fopen($file, 'r');
$i = 0;

while ($line = fgetcsv($fh, 1000, "\t") !== false) {
  $cols[] = $line;

  if($i == 19) { break; }
    $i++;
  }

echo "<pre>";
print_r($cols); 
echo "</pre>";

Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
[4] => 1
[5] => 1
[6] => 1
[7] => 1
[8] => 1
[9] => 1
[10] => 1
[11] => 1
[12] => 1
[13] => 1
[14] => 1
[15] => 1
[16] => 1
[17] => 1
[18] => 1
[19] => 1
)

I've tried changing \t to \n but that didn't change the result. If I can do this all in one step that would be better, check the second item in the row and if it's a one then add the first item (email) into the array. Otherwise don't. At this point I'll take what I can get! Any ideas or suggestions?


I now am getting the items in the array, but it's merging the columns into one array item:

Array
(
[0] => Array
    (
        [0] => EMAIL    1
    )
)

Is there a way for me to spit out the columns into separate keys? So:

Array
(
[0] => Array
    (
        [0] => EMAIL
        [1] => 1
    )
)

回答1:


You need to wrap your while statement with more ( )

while ($line = fgetcsv($fh, 1000, "\t") !== false) {

should be

while (($line = fgetcsv($fh, 1000, "\t")) !== false) {


来源:https://stackoverflow.com/questions/19452541/php-tab-delimited-text-file-into-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!