Reputation: 4235
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?
Upvotes: 0
Views: 89
Reputation: 14237
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
Upvotes: 0
Reputation: 219814
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:
Then each row should be populated with the data for each person
. The first column being a unique ID.
Upvotes: 1
Reputation: 324640
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.
Upvotes: 1