繁体   English   中英

如何在 PHP 中将 .csv 文件解析为多维数组?

[英]How to parse a .csv file into a multidimensional array in PHP?

我是 PHP 新手,我正在尝试制作一个与 .csv 文件通信的待办事项列表。 到目前为止,我已经设法编写了一个将用户输入写入 csv 文件的函数,但我坚持编写一个函数来解析(我什至不确定这是否是正确的术语)的每一行.csv 文件转换为多维数组,以便我可以在 PHTML 文件中方便地显示列表的每一行。

这是我到目前为止所拥有的:

`<?php
//
// ─── DATA ────────────────────────────────────────────────────────────────────
//

$user_entry = array(
    'title' => '',
    'description' => '',
    'date' => '',
    'priority' => ''
);

// puts the data the users entered into an array
$user_entry['title'] = $_POST['title'];
$user_entry['description'] = $_POST['description'];
$user_entry['date'] = $_POST['date'];
$user_entry['priority'] = $_POST['priority'];

//
// ─── FUNCTIONS ──────────────────────────────────────────────────────────────────
//

function writeInList() {
    //parses the $user_entry array into the .csv file
    global $user_entry;
    $file = fopen("todo.csv","a");
    fputcsv($file, $user_entry, ",");
    fclose($file);
}

function displayList() {
    //That's where I'm stuck.
    $file = fopen("todo.csv","r");
    $fileCountable = file("todo.csv");
    for ($i = 0; $i < count($fileCountable); $i++) {
        $csvContent = fgetcsv($file, 1000, ",");
        foreach ($csvContent as $value){
            $var[$i] = $value;
        }
        echo '<br>';
    }
    fclose($file);
}

//
// ─── MAIN CODE ─────────────────────────────────────────────────────────────
//

writeInList();

include 'todolist.phtml';`

如果之前已经讨论过,我很抱歉。 我已经搜索了很多并发现了类似的问题,但无法让它在我自己的代码中工作。 如果有人花时间查看我的代码,非常感谢!

这也是我第一次在这里发帖,所以我希望我做得对。

你做得很好。 您可以查看fgetcsv文档了解更多信息。 我会改变你的函数,这样它就会把参数作为输入(尽量避免使用global

// insert data
function writeInList($user_entry, $path ) {
    $file = fopen($path ,"a");
    fputcsv($file, $user_entry, ",");
    fclose($file);
}

//extract data
function getList($path, $limit = 100000) {
    $file = fopen($path, "r");
    if (!$file) return null; // or throw error or print to log
    $allRows = []; //
    while (($data = fgetcsv($file, $limit, ",")) !== FALSE) {
        $allRows[] = $data; // as fgetcsv return array already exlode by "," 
    }
    fclose($file);
    return $allRows; 
}

现在您有从getList返回的 2-Dim 数组。 使用 as getList("todo.csv")并按您的getList("todo.csv")显示。

希望有帮助!

暂无
暂无

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

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