我想有一个循环读取变量中的第一个标头存储然后阅读详细信息,每次它点击'我'它将该行上传到MYSQL。
解析文件有多种方法。
下面的方法利用的explode()
为H和I
所以,你有一个“外循环”为H(H header1 yyyy I detailofheader1 I detailofheader1
) - 来处理单独报头。
而我的一个“内循环”(header1 yyyy I detailofheader1 I detailofheader1
) - 处理标题数据本身和细节。
SQL明智:
- 我不知道你的SQL模式 - 只是猜测周围的模式。
- 我在哪里使用
echo $sql
- 你可以执行查询。
- 这个例子SQL,逃生得当,使其安全
反正这里的东西一起玩。希望让你开始...
<?php
// example data to work with
$string = 'H header1 yyyy I detailofheader1 I detailofheader1 H header2 xxxx I detailofheader2 I detailofheader2';
// later just
// $string = file("file.txt");
// get rid of the first H (to ease exploding/no empty first array item)
$string = ltrim($string, 'H');
// explode string into array - by using H as char for the split
$headers = explode('H', $string);
foreach($headers as $idx => $line)
{
$line = trim($line); // remove spaces at begin/end
//echo 'Processing: [' . $idx . '] ' . $line . PHP_EOL;
// second explode, this time using "I"
$data = explode('I', $line);
foreach($data as $dataIdx => $details)
{
$details = trim($details); // remove spaces at begin/end
//echo ' ' . $details . PHP_EOL;
// first dataIdx is the header data "header1 yyyy"
if($dataIdx === 0) {
// string contains a space, split
$headerItems = explode(' ', $details);
$headerNumber = trim($headerItems[0]); // header1
$headerString = trim($headerItems[1]); // yyyy`
// => insert the header
$sql = "INSERT INTO table_headers (id, name) VALUES ('$headerNumber',' $headerString')";
echo $sql . PHP_EOL;
// we are done, skip to next element
continue;
}
// else its a "detailofheaderX"
// so use details in the insert query
$sql = "INSERT INTO table_data (header_id, detail) VALUES ('$headerNumber', '$details')";
echo $sql . PHP_EOL;
}
}
我这里看不到一个循环 – developerwjk