我有一个文本文件,其中包含一些我想放入 2D 数组中的东西。该文本文件由长度相等的句子组成。如何将每个单词放入数组中?
文本文件的示例是 -
这是堆栈溢出
我是用户
此文件每行包含 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];
}
}
}
}
}
}
任何帮助将不胜感激。谢谢
这应该适合您:
只需将您的文件读入一个带有 file()
的数组,并在每行中用一个带有 array_map()
的空格explode()
。
$lines = array_map(function($v){
return explode(" ", $v);
}, file("yourTextFile.txt", FILE_IGNORE_NEW_LINES |FILE_SKIP_EMPTY_LINES));