我的 Excel 工作表中有数据,如下所示。
我必须读取数据(我将尝试 csv 格式,请提出其他建议)。使用PHP读取数据...
创建两个表,希望如下所示。
1.
2.
- 我期待这样的 ExtJs 树。
我在步骤 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/