在PHP中创建从不同文件读取的数组

在PHP中创建从不同文件读取的数组,php,php-7,Php,Php 7,我正在尝试以下方法 我有不同的文件(8个文件)存储如下值: 1 2 3 4 5 6 7 8 9 10 11 12 .................... $myfile = fopen("textoPrueba.txt", "r", "/home/berni/Documentos/Vesta1"); // Output one character until end-of-file while(

我正在尝试以下方法

我有不同的文件(8个文件)存储如下值:

1      2      3      4      5      6
7      8      9      10     11     12
....................
$myfile = fopen("textoPrueba.txt", "r", 
"/home/berni/Documentos/Vesta1");
// Output one character until end-of-file
while(!feof($myfile))
{
   echo fgetc($myfile);
}
fclose($myfile);
我想同时读取8个文件,并创建一个数组来存储每个文件的第一个值,另一个数组包含第二个元素,依此类推

例如,如果file1的第一个元素是
1
,则在file2
8
中,…,在file8
23
中;此迭代中的结果数组为:

first_array = [1, 8, ....., 23]
我在用PHP读取文件时做了一些测试,如下所示:

1      2      3      4      5      6
7      8      9      10     11     12
....................
$myfile = fopen("textoPrueba.txt", "r", 
"/home/berni/Documentos/Vesta1");
// Output one character until end-of-file
while(!feof($myfile))
{
   echo fgetc($myfile);
}
fclose($myfile);
这段代码只显示文件的元素,但我希望在迭代中获取特定元素

有人能给我一个提示吗?提前谢谢


(注意:文件包含超过一百万个元素)

做出以下假设:

  • 每个文件都有一个由空格分隔的数字字符串
  • 数字不超过十亿
从您提供的代码开始,提取每个文件的第一个元素的代码:

$myfile = fopen("textoPrueba.txt", "r", "/home/berni/Documentos/Vesta1");

// get the first 10 elements one at a time
$str = array();
for($i=0; $i<10; $i++) {
  // get the first 10 elements one at a time
  $str[] = fgetc($myfile);
}
fclose($myfile);

// squish them into a single string
$temp = join($str);

// explode it into an array separated by spaces
$split = explode(' ', $temp);

// get the first number
$first_element_of_file = $split[0];
$myfile=fopen(“textoPrueba.txt”、“r”、“home/berni/Documentos/Vesta1”);
//一次获取前10个元素
$str=array();

对于($i=0;$i另一个选项是,在我们将
文件获取内容
或读取我们的文件后,我们将使用一个简单的表达式并使用
预匹配
收集我们的数字:

$re = '/([0-9]+)/m';
$str = '1      2      3      4      5      6
7      8      9      10     11     12
1      2      3      4      5      6
1      2      3      4      5      6
';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

foreach ($matches as $key => $numbers) {
    foreach ($numbers as $key2 => $number) {
        echo $number . "\n";
    }
}
var\u dump($matches);

我最好的提示是使用数据库;这就是它们的用途。如果我理解正确,每个文件都有以空格分隔的数字?如果是,请读取前5个左右的字符,将其放入字符串并在空格上分解。然后获取第一个数组元素。谢谢你的回答,但首先我想学习从不同的文件读取cre我吃了我需要的数组,因为在数据库中插入800万个寄存器我觉得太过分了。再次感谢你!数据的初始加载可能需要一段时间,但性能的提高比设置它的任何麻烦都值得。学习如何以文件方式进行操作没有错,只要你知道最终会发生什么很可能是一个弗兰肯斯坦(而且是一个非常慢的人)与在数据库中执行相比,800万对数据库来说算不了什么谢谢你们的信息!!我会搜索如何实现批量插入的信息无意冒犯,但是对于这项任务来说regex似乎有点太多了。OP甚至没有提到这是一种可能,这可能会让他们不知所措。Uoooh谢谢!!我对常规插入不太了解表达式,但它可以帮助我访问元素。一个问题,为什么要在每个位置创建一个包含两个相同元素的数组?[0]=>array(2){[0]=>string(1)“1”[1]=>string(1)“1”…另一个问题:使用您的代码,我对这样的数字有问题0.1112222333344,这种数字的正则表达式必须是什么?Thnk u$re='([0-9.]+)m';很好!!谢谢你,我会尽快发布我的解决方案…再次感谢你的帮助谢谢你Tom!!因此,对于使用8个文件,我必须实现与你提供的相同的代码,但是在for()中提到每个文件,不是吗?我回家后会尝试你的代码,谢谢!!