开发者

PHP / MySQL formatinng: An example of how this type of data is used?

Sorry in advance for the kind of odd/vague question :). I've come across this kind of formatting stored in MySQL databases on several occasions now and I'm wondering how the data is used? For example, this line of code was from the bbPress forums plugin bb_message.

a:8:{s:9:"max_inbox";i:50;s:13:"auto_add_link";b:1;s:9:"email_new"开发者_如何学编程;b:1;s:11:"email_reply";b:1;s:9: "email_add";b:1;s:13:"email_message";b:0;s:16:"threads_per_page";i:0;s:7:"version";s:3:"1.0";}

What's up with the characters and letters? For example I'm guessing s:9:"max_inbox" refers to a string of nine characters and the string is max_inbox. But how is this data manipulated with PHP (and why would the s:9 be necessary) when its pulled from the database?

Thanks all!


I believe this is a string that is generated by PHP's serialize function. This function enables you to represent a (complex) object or array as a string.

Furthermore I think the numbers you are refering to are probably needed to make tokenizing (not sure if that is the appropriate term here) the string back to it's relevant parts easier. Without having given it much thought, I presume it is meant to circumvent situations where the tokenizer might choke on actual values of the serialized object that contain delimiters (:;").


Use PHP's unserialize function to decode the strings like that.

unserialize PHP docs

This string decodes to this array like so:

php > $f='a:8:{s:9:"max_inbox";i:50;s:13:"auto_add_link";b:1;s:9:"email_new";b:1;s:11:"email_reply";b:1;s:9:"email_add";b:1;s:13:"email_message";b:0;s:16:"threads_per_page";i:0;s:7:"version";s:3:"1.0";}';
php > var_dump(unserialize($f));
array(8) {
["max_inbox"]=>
int(50)
["auto_add_link"]=>
bool(true)
["email_new"]=>
bool(true)
["email_reply"]=>
bool(true)
["email_add"]=>
bool(true)
["email_message"]=>
bool(false)
["threads_per_page"]=>
int(0)
["version"]=>
string(3) "1.0"
}

The reason for storing data like this is that you can store multiple parameters in one database field.

Storing serialized arrays allows you to not worry about the schema of your database. Friendfeed does this with MySQL for instance, and it's also similar to the style of the 'NoSQL' storage systems like MongoDB. I prefer to use JSON over PHP serialize, myself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜