简体   繁体   English

我们如何将文件中的文本(逐个单词)转换为PHP中的2D数组?

[英]How do we get text from a file (word-by-word) into a 2D array in PHP?

I have a text file with some stuff that I would like to put into a 2D array. 我有一个文本文件,其中包含一些我想放入2D数组中的内容。 That text file comprises of sentences of equal length. 该文本文件包含相等长度的句子。 How do I put each word into an array? 如何将每个单词放入数组?

Example of text file is - 文本文件的示例是-

This is stackoverflow 这是stackoverflow

I am user 我是使用者

This file contains 3 words in each line 该文件每行包含3个字

This - at [0][0] position
is - at [0][1] position
stackoverflow - at [0][2] position

I - at [1][0] position
am - at [1][1] position
user - at [1][2] position

I made something like this but doesn't seem to work out. 我做了这样的事情,但似乎没有解决。

$word_count = $word_length = 0;

if ($fh = fopen('array.txt','r')) {
    while (! feof($fh)) {
      if ($s = fgets($fh,1048576)) {
         $words = preg_split('/\s+/',$s,-1,PREG_SPLIT_NO_EMPTY);
         foreach ($words as $word) {
           $word_count++;
           $word_length += strlen($word);

           $array = array();
           for($i=$a;$i<($word_count/4);$i++)    
           {
            for($j=$b;$j<4;$j++)
            { 
             $array[$i][$j]=$words[$j];
            }
           }
                                   }
                                   }
                        }
                                   }

Any help would be appreciated. 任何帮助,将不胜感激。 Thanks 谢谢

This should work for you: 这应该为您工作:

Just read your file into an array with file() and explode() each line by a space with array_map() . 刚刚看了你的文件到一个数组与file()explode()用空格每行array_map()

$lines = array_map(function($v){
    return explode(" ", $v);
}, file("yourTextFile.txt", FILE_IGNORE_NEW_LINES |FILE_SKIP_EMPTY_LINES));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM