【问题标题】:Read the excel data and inserting in below format读取excel数据并以以下格式插入
【发布时间】:2012-11-21 13:48:03
【问题描述】:

我在 excel 表中有数据,如下所示。

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

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

1.

2.

  1. 我期待这样的 ExtJs 树。

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

【问题讨论】:

  • 所以你在 excel 中有一个数据透视表?并且您希望将关系放入带有标识符而不是值本身的 sql 数据库中?
  • 为什么是 2 张桌子?一个应该做的。可食用的表、字段、id、名称、类型(水果或蔬菜)
  • 我在 excel 中的数据是多级的。最多可以有 5 个级别的父级、子级..

标签: php mysql 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();

【讨论】:

    【解决方案2】:

    类似

    lastvalues=array(); // To hold the last value on each level
    data=array();
    foreach($lines as $i=>$line){
      elems=explode(',',$line);
      foreach($elems as $n=>$e){
         if($e>''){
            $data[$i]=$e;
            lastvalues[$n]=$i;
            if($n){ // makes no sense for 0th level
               $tree[]=array('parent'=>$lastvalues[$n-1],child=>$i);
            }
         }
      }
    }
    

    应该给你数据结构。您可以使用 SQL 插入而不是 $data 和 $tree 数组。

    【讨论】:

      猜你喜欢
      • 2021-11-23
      • 1970-01-01
      • 2012-08-20
      • 1970-01-01
      • 2018-05-13
      • 2016-05-13
      • 2012-11-15
      • 2016-10-28
      • 1970-01-01
      相关资源
      最近更新 更多