我有以下PHP代码,它从格式化的文本文件中读取数据,数据以逗号分隔。
// Create database gameDB
if (mysql_query('create database gameDB', $connection)) {
echo "Database gameDB created successfully.\n";
} else {
echo 'Error creating database: ' . mysql_error() . "\n:";
}
// select which database to use
mysql_select_db('gameDB', $connection);
// create table xyzcoord if it doesn't already exist
mysql_query('CREATE TABLE IF NOT EXISTS xyzcoord (
Frame varchar(100),
X varchar(100),
Y varchar(100),
Z varchar(100))', $connection);
$wx = array_map('trim',file("20-frames-xyz-coordinates.txt"));
$newwx = array();
foreach($wx as $i => $line)
{
if ($i > 1)
{
$tmp = array_filter(explode(' ',$line));
$q = "insert into xyzcoord (Frame, X, Y, Z) values ('" . implode("','",$tmp) . "')";
$rw = mysql_query($q) or die("Problem with the query: $q<br>" . mysql_error());
}
}
?>
我的问题是我有一个不同的文本文件我需要阅读,其中数据是非结构化的,格式如下,为60帧。
(new line) Frame_0100
(new line) X_coordinates
(new line) 23.90,23.90,23.94,23.98,24.02,24.02,24.06
(new line) Y_coordinates
(new line) 5.55,6.15,5.55,5.55,5.51,5.55,5.51
(new line) Z_coordinates
(new line) 0.00,0.00,0.00,0.00,0.00,0.00,0.00
(new line)
(new line) Frame_0101
(new line) X_coordinates
(new line) 23.90,23.90,23.94,23.98,24.02,24.02,24.06
(new line) Y_coordinates
(new line) 5.55,6.15,5.55,5.55,5.51,5.55,5.51
(new line) Z_coordinates
(new line) 0.00,0.00,0.00,0.00,0.00,0.00,0.00
(new line)
(new line) Frame_0102
(new line) X_coordinates
(new line) 23.90,23.90,23.94,23.98,24.02,24.02,24.06
...etc
我希望读取这些尚未格式化的数据,并将其存储在MySQL DB中。我不知道如何以PHP格式读取数据。我考虑过使用JSON。任何帮助表示赞赏。
答案 0 :(得分:0)
我假设前两行是空白的,然后数据在第3行开始不间断(index = 2);如果错误的话,必须改变顶部的数字。否则,用这个替换你的foreach循环,它应该工作:
foreach($wx as $i => $line)
{
if ($i > 1 and ($i-2)%4 == 0)
{
$q = "insert into xyzcoord (Frame, X, Y, Z) values ('" . $line . str_replace('X_coordinates ','',$wx[$i+1]) . str_replace('Y_coordinates ','',$wx[$i+2]) . str_replace('Z_coordinates ','',$wx[$i+3]) . "')";
$rw = mysql_query($q) or die("Problem with the query: $q<br>" . mysql_error());
}
}