简体   繁体   English

在多维数组基于PHP的CSV解析中添加元素

[英]Add an element in multidimentional array PHP based CSV Parsing

I have csv, with a lot of column, 我有csv,有很多专栏文章,

+---------+------------------+
|   NAME  |  ADDRESS         |
+---------+------------------+
|   JOHN  |  ADDRESS  1      |
|   MARY  |  ADDRESS  2      |
+---------+------------------+

And this one will be uploaded to the web app. 并将其上传到Web应用程序。 My question is, I want to store the name of file in additional column (last column in each row.) 我的问题是,我想将文件名存储在其他列(每行的最后一列)中。

+---------+------------------+-------------+
|   NAME  |  ADDRESS         |  NAME FILE  |
+---------+------------------+-------------|
|   JOHN  |  ADDRESS  1      |    MAIN.CSV |
|   MARY  |  ADDRESS  2      |    MAIN.CSV |
+---------+------------------+-------------+

This is my code : 这是我的代码:

    $csv = $this->input->post('path'); //PATH CSV
    $nama_file = $this->input->post('nama'); // NAME OF FILE

    $tryOne = array();

    if (file_exists($csv)) {
        $file = fopen($csv, 'r'); // r flag is for readonly mode
        fgetcsv($file, 1000, ",");
        while (( $line = fgetcsv($file) ) !== false) { // if line exists
            $tryOne[] = $line; // add to array      

        }
        fclose($file);
    }

THE RESULT LIKE THIS 像这样的结果

Array
(
[0] => Array
    (
        [0] => JOHN
        [1] => ADDRESS 1
    )

[1] => Array
    (
        [0] => MARY
        [1] => ADDRESS 2
    )
)

Any help it so appreciated. 任何帮助,它表示赞赏。

Try below code... I am considering you are getting filename in $nama_file variable. 尝试下面的代码...我正在考虑您正在$ nama_file变量中获取文件名。

$csv = $this->input->post('path'); //PATH CSV
    $nama_file = $this->input->post('nama'); // NAME OF FILE

    $tryOne = array();

    if (file_exists($csv)) {
        $file = fopen($csv, 'r'); // r flag is for readonly mode
        fgetcsv($file, 1000, ",");
        while (( $line = fgetcsv($file) ) !== false) { // if line exists
            array_push($line, $nama_file);
            $tryOne[] = $line; // add to array      

        }
        fclose($file);
    }

$line is and array so you can append the filename to it. $line是和数组,因此您可以将文件名附加到它。

while (( $line = fgetcsv($file) ) !== false) {
    $line[] = $nama_file;
    $tryOne[] = $line;
}

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

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