Question

Say I have a String 030512 Jack 25 Male\n030513 David 23 Male\n030514 ..., how to extract the info from this String as a two dimensional table in PHP?

In Java, I can use StringTokenizer, like:

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));
}

Actually, my final goal is extracting this "table-like" info and store them into a Mysql database.

I am not familiar with PHP, could you show me how to do this in PHP, or what is a good practice to implement this two-dimensional data insertion into a Mysql database?

Was it helpful?

Solution 2

Not fancy but easier to understand in my opinion (requires that the string doesn't end with newline though, and that the information is always correctly formatted):

$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);
}

You could of course execute the queries in the first loop instead if thats what you want.

OTHER TIPS

You can use the explode or split functions. E.g.

$records = explode("\n", $raw_data);
foreach($record in $records) {
    $fields = explode(" ", $record);
    $id = fields[0];
    $name = fields[1];
    ///....
}

You can use explode() coupled with list():

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

Edit:

Updated the solution to correct a misunderstanding of the original data structure.

You could do like this

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

$array = array_map(function($v) {
    return explode(' ', $v);
}, explode("\n", $string));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top