php - 读取excel数据并按以下格式插入

标签 php mysql excel csv

我的 Excel 工作表中有数据,如下所示。

enter image description here

我必须读取数据(我将尝试 csv 格式,请提出其他建议)。使用PHP读取数据...

创建两个表,希望如下所示。

1.

enter image description here

2.

enter image description here

  • 我期待这样的 ExtJs 树。
  • enter image description here

    我在步骤 1 中遇到问题。我该如何读取我的 Excel 工作表、csv 文件,以便数据库像表 1 一样更新

    最佳答案

    这是一个解决方案,尽管我没有像您一样维护相同的 Data_Id(您似乎按深度和节点增加了 id,但我只是使用了行号)。

    <?php
    $data = <<<EOT
    Eatables,,
    ,Fruits,
    ,,Apple
    ,,Mango
    ,Vegetables,
    ,,Tomatoes
    ,,Potatoes
    EOT;
    
    $mysqli = new mysqli("localhost", "username", "password", "test");
    
    $dataInsertStatement = $mysqli->prepare("INSERT INTO Data (Data_Id, Data_Value) VALUES (?, ?)");
    $treeInsertStatement = $mysqli->prepare("INSERT INTO Tree (parent_id, child_id) VALUES (?, ?)");
    
    $lines = explode("\n", $data);
    
    $path = array();
    
    foreach ($lines as $rowNum => $line) {
        // convert line of csv to array
        $row = str_getcsv($line);
        // loop through the row's fields and find the one that's not empty
        foreach ($row as $column => $value) {
            if (!empty($value)) {
                // use row number + 1 as $Data_Id
                $Data_Id = $rowNum + 1;
    
                // track our depth in the tree
                $path[$column] = $Data_Id;
    
                // insert the data
                $dataInsertStatement->bind_param('is', $Data_Id, $value);
                $dataInsertStatement->execute();
    
                // check if this node has a parent
                if (isset($path[$column - 1])) {
                    // connect this node to its parent in the tree
                    $treeInsertStatement->bind_param('ii', $path[$column - 1], $Data_Id);
                    $treeInsertStatement->execute();
                }
    
                continue;
            }
        }
    }
    
    $mysqli->close();
    

    关于php - 读取excel数据并按以下格式插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13494698/

    相关文章:

    php - 如何在 Laravel 5 中设置基本路径

    php - 如何使用SELECT INTO OUTFILE写入/tmp以外的目录?

    php - 将我的 RESTful API 仅限于我的应用程序

    vba - 无法使用 VBA 从 Power Pivot 数据模型创建数据透视表

    excel - 使用 Power Query 创建的数据模型中的表之间的 Power Pivot 关系

    php - 一个文件中的PHP CMS

    php - 使用 whois 检查子域名

    php - 我在使用 mysqli free() 成员函数时遇到问题

    Python pymysql datetime.datetime元组到时间戳

    excel - 计算增量空白单元格直到下一个非空单元格(仅限公式)