0

I'm working on a system that stores an array of objects in the db in a certain way.

Like this:

key             | value
------------------------------
person_0_name   | David
person_0_age    | 32
person_0_job    | Programmer
person_1_name   | Sue
person_1_age    | 26
person_1_job    | Teacher
person_2_name   | Jon
person_2_age    | 40
person_2_job    | Bus Driver

Is this a made up format? I'm wondering if there's an easy way to unserialize this?

3 Answers 3

1

Well, you'd probably want something like this:

$lines = explode("\n",$data);
$keys = array_shift($lines);
array_shift($lines); // discard the line of dashes
$keylist = Array();
foreach(explode("|",$keys) as $k) {
    $keylist[] = trim($k);
}
$out = Array();
foreach($lines as $line) {
    foreach(explode("|",$line) as $i=>$l) {
        $out[$keylist[$i]] = trim($l);
    }
}
// var_dump($out);

The only downside is that it doesn't keep trailing spaces if there are any in the data - probably not a huge loss.

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry I think I confused you. The table in the question has two columns and each line is actually a row.
1

This is a made up format and clearly done by someone who does not understand deatabase design. You need to make a table for persons with four columns:

  1. id
  2. name
  3. age
  4. job

Then each row should be populated with the data for each person. The first column being a unique ID.

Comments

0

I think the above are a little conveluted. Depending on how you are accessing the database, the following can easily be adjusted. I used the simplest form of DB connection.

The code:

<?php
$m = mysql_connect('localhost', 'root', 'stack');
mysql_select_db('stack');

$q = mysql_query('SELECT * FROM example');

$arr = array();

while($row = mysql_fetch_assoc($q)){
    $arr[substr($row['key'],0, 8)][substr($row['key'],9)] = $row['value'];
    print_r($arr);
}

The result looks like

Array
(
    [person_0] => Array
    (
        [name] => David
        [age] => 32
        [job] => Programmer
    )

)

Let me know if you have any questions.. In short, the script does a substring on the key field to create array keys based on the person/value.

Enjoy - sEZ

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.