【问题标题】:How do we get text from a file (word-by-word) into a 2D array in PHP?我们如何将文件中的文本(逐字)放入 PHP 中的二维数组中?
【发布时间】:2015-09-01 16:53:23
【问题描述】:

我有一个文本文件,其中包含一些我想放入二维数组的内容。该文本文件由等长的句子组成。如何将每个单词放入一个数组中?

文本文件示例是 -

这是堆栈溢出

我是用户

此文件每行包含 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

我做了类似的东西,但似乎没有成功。

$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];
            }
           }
                                   }
                                   }
                        }
                                   }

任何帮助将不胜感激。谢谢

【问题讨论】:

  • 您应该修正代码的格式。最后的} 看起来像是一场非常糟糕的太空侵略者游戏。
  • 仅供参考:您可以接受对您帮助最大并解决了您的问题的答案 (meta.stackexchange.com/q/5234)

标签: php arrays parsing file-handling


【解决方案1】:

这应该适合你:

只需将您的文件读入一个包含file()explode() 的数组,每行用array_map() 加一个空格。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 2012-11-19
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多