0

假设我有一个 String 030512 Jack 25 Male\n030513 David 23 Male\n030514 ...,如何从这个 String 中提取信息作为 PHP 中的二维表?

在 Java 中,我可以使用StringTokenizer,例如:

StringTokenizer lineTokenizer = new StringTokenizer("030512 Jack ...", "\n");
List<Student> students = new ArrayList<Student>();

while(lineTokenizer.hasMoreTokens()) {
    String line = lineTokenizer.nextToken();
    StringTokenizer itemTokenizer = new StringTokenizer(line, " ");
    String id = itemTokenizer.nextToken();
    String name = itemTokenizer.nextToken();
    String age = itemTokenizer.nextToken();
    String sext = itemTokenizer.nextToken();
    students.add(new Student(id, name, age, sex));
}

实际上,我的最终目标是提取这个“类似表格”的信息并将它们存储到 Mysql 数据库中。

我对PHP不熟悉,你能告诉我如何在PHP中做到这一点,或者将这种二维数据插入Mysql数据库的好做法是什么?

4

4 回答 4

2

您可以使用分解或拆分功能。例如

$records = explode("\n", $raw_data);
foreach($record in $records) {
    $fields = explode(" ", $record);
    $id = fields[0];
    $name = fields[1];
    ///....
}
于 2013-02-16T00:25:17.720 回答
1

您可以explode()结合使用list()

foreach (explode("\n", $yourString) as $line) {
    list($id, $name, $age, $sex) = explode(' ', $line);
    // ...
}

编辑:

更新解决方案以纠正对原始数据结构的误解。

于 2013-02-16T00:24:02.880 回答
1

在我看来,这不是花哨但更容易理解(要求字符串不以换行符结尾,并且信息的格式始终正确):

$students = array();

//no newline at the end, or you'll have to add a check for that in the loop.
$str = "030512 Jack 25 Male\n030513 David 23 Male";

foreach(explode("\n", $str) as $student_str) {
    list($id, $name, $age, $sex) = explode(" ", $student_str);
    array_push($students, array(":id"=>$id,":name"=>$name, ":age"=>$age, ":sex"=>$sex));
}

//For the DB part which has been quite absent.
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$query = "INSERT INTO students (id, name, age, sex) VALUES (:id, :name, :age, :sex)";
$prepared_query = $conn->prepare($query);

foreach($students as $student) {
    $prepared_query->execute($student);
}

如果那是您想要的,您当然可以在第一个循环中执行查询。

于 2013-02-16T00:37:37.593 回答
0

你可以这样做

$string = "030512 Jack 25 Male\n030513 David 23 Male\n030514";

$array = array_map(function($v) {
    return explode(' ', $v);
}, explode("\n", $string));
于 2013-02-16T00:27:35.187 回答