【问题标题】:Reading unstructured data using PHP into MySQL Database Problem使用 PHP 将非结构化数据读入 MySQL 数据库问题
【发布时间】:2011-08-13 15:13:41
【问题描述】:

我有以下 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。任何帮助表示赞赏。

【问题讨论】:

  • 所以每帧都有很多 x,y,z 坐标?
  • 是的,我需要在 MySQL 中将其读取为 Frame1(row) - X(column) Y(column) Z(column)。任何想法表示赞赏。

标签: php mysql database json phpmyadmin


【解决方案1】:

我假设前两行是空白的,然后数据从第 3 行开始不间断(索引 = 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());
        }
}

【讨论】:

  • 对不起,我写错了。数据从第三行开始,我对此进行了编辑。我可以改变你上面的方法以适应。感谢您的帮助。
  • 老实说,我无法理解您的 if 语句。我是 PHP 新手,所以我希望你能原谅我的天真/白痴。我知道它只是将索引更改为 3,但是您对其进行编码的方式我无法弄清楚如何做到这一点。如果你能解释一下那就太好了。
猜你喜欢
  • 1970-01-01
  • 2021-07-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-18
  • 1970-01-01
  • 2021-06-16
  • 2018-07-06
  • 1970-01-01
相关资源
最近更新 更多