在PHP中使用while()合并数组
I found the need to use element keys as identifiers and therefore stumbled upon the following predicament.
I am reading a file and parsing it in order to extract the filenames and then work with them. As I am looping through all the lines in the file, I am creating a new array for every match to the regular expression:
$file = fopen('/home/user/log.txt', 'r');
if ($file) {
while (($line = fgets($file)) !== false) {
if (preg_match('~^/[^:]+~m', $line, $files)) { //match everything until the first ':' to get file names
var_dump($files);
}
}
}
Thus, I get:
array (size=1)
0 => string '/home/user/whatever.php' (length=23)
array (size=1)
0 => string '/home/user/run.php' (length=18)
array (size=1)
0 => string '/home/user/sth.php' (length=18)
I would like to merge them all into one single array so that they may have different keys. Can that be achieved in this scenario or should I consired rewriting the loops?
我发现需要使用元素键作为标识符,因此偶然发现了以下困境。 p>
我正在读取文件并解析它以提取文件名然后使用它们。 当我循环遍历文件中的所有行时,我正在为正则表达式的每个匹配创建一个新数组: p>
$ file = fopen('/ home / user /log.txt','r');
if($ file){
while(($ line = fgets($ file))!== false){
if(preg_match('〜^ / / [^:] + ~m',$ line,$ files)){//匹配所有内容,直到第一个':'获取文件名
var_dump($ files);
}
}
}
code> pre>
因此,我得到: p>
array(size = 1)
0 => string'/home/user/whatever.php'(length = 23)
array(size = 1)
0 => string'/home/user/run.php'(length = 18)
array(size = 1)
0 => string'/home/user/sth.php'(length = 18)
code> pre>
我想将它们全部合并为一个数组,以便它们可能有所不同 键。 可以在这种情况下实现,还是我应该重写循环? p>
div>
Do something like this instead to add them to an array as you loop:
$file = fopen('/home/user/log.txt', 'r');
$array = [];
if ($file) {
while (($line = fgets($file)) !== false)
{
if (preg_match('~^/[^:]+~m', $line, $files))
{ //match everything until the first ':' to get file names
array_push($array, $files);
}
}
}
var_dump($array);