简体   繁体   English

读取多个.txt文件,并使用php将主题保留在一个简单的数组中

[英]Read multiple .txt files and keep theme in a single simple array with php

I'm trying to read multiple files and put them in a single array. 我正在尝试读取多个文件,并将它们放在单个数组中。

My code look like this : 我的代码如下所示:

      $directory = "./folder/folder/"
        $file_array = array();
        if ($condition == 'TRUE'){
        $file_array = array(
                    'file_1.txt',
                    'file_2.txt',
                    'file_3.txt',
                    'file_4.txt'
                );
        }

        foreach($file_array as $file){
                        $single_file_arr[] = file($directory . $file);
                    }
    echo "<pre>";
    print_r($single_file_arr);
    echo "</pre>";

//OUTPUTS:
Array
(
    [0] => Array
        (
            [0] => value1
            [1] => value2
            [2] => value3
        )
    [1] => Array
        (
            [0] => value4
            [1] => value5
        )
    [2] => Array
        (
            [0] => value6
            [1] => value7
        )
    [3] => Array
        (
            [0] => value8
            [1] => value9
        )

)

So how To use array_merge($single_file_arr) to keep all the arrays in a single array. 那么如何使用array_merge($single_file_arr)将所有数组保持在单个数组中。

Where am wrong? 哪里错了? I want to be in one single array. 我想成为一个单一的阵列。

//I WANT TO BE :

Array
    (
        [0] => value1
        [1] => value2
        [2] => value3
        .
        .
        .
        [8] => value9
    )
$directory = "./folder/folder/"
$file_array = [];
if ($condition == 'TRUE') {
    $file_array = [
        'file_1.txt',
        'file_2.txt',
        'file_3.txt',
        'file_4.txt'
    ];
}

$single_file_arr = [];
foreach ($file_array as $file) {
    $single_file_arr = array_merge($single_file_arr, file($directory . $file));
}

You are using file ( http://php.net/manual/en/function.file.php ) function, that returns contents of the file as an array. 您正在使用文件( http://php.net/manual/en/function.file.php )函数,该函数以数组形式返回文件的内容。 So you should use file_get_contents ( http://php.net/manual/en/function.file-get-contents.php ) to read contents directly as a string. 因此,您应该使用file_get_contents( http://php.net/manual/en/function.file-get-contents.php )直接以字符串形式读取内容。

So change... 所以改变...

file($directory . $file);

to

file_get_contents($directory . $file);

and it will be like you needed. 就像您需要的。

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

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