PHP将数组转成字符串存储及字符串取出转成数组(serialize & unserialize)

PHP将数组转成字符串存储及字符串取出转成数组(serialize & unserialize)
php-string-array-serialize-and-unserialize

假如你要保存一个数组到数据库里
思路应该是将数组转成字符串,
但要考虑到取出来时数据完整及便利
PHP里有两个函数非常好用serialize和unserialize

下面看一个实例:

<?php
// $Id: test3.php,v 1.0 2011-6-7  goba Exp $
 
/**
 * 测试PHP存储数值
 *
 * @author Lok
 */
 
 
$config = array (
	'host' => 'localhost',
	'user_name' => 'root',
	'password' => '',
	'db_name' => 'ecshop',
	'charset' => 'utf8',
	'remark' => array ('note' => '要注意密码的安全', 'author' => 'Lok')
);
 
 
$str = serialize($config);
$arr = unserialize($str);
 
echo '--------str--------<br />';
var_dump($str);
echo '<br />-------arr----------<br />';
var_dump($arr)
?>

结果:

--------str--------
string(221) "a:6:{s:4:"host";s:9:"localhost";
			s:9:"user_name";s:4:"root";
			s:8:"password";s:0:"";
			s:7:"db_name";s:8:"ecshop";
			s:7:"charset";s:4:"utf8";
			s:6:"remark";a:2:{s:4:"note";s:24:"要注意密码的安全";
			 		          s:6:"author";s:3:"Lok";}}" 
-------arr----------
array(6) { ["host"]=> string(9) "localhost" 
	       ["user_name"]=> string(4) "root" 
	       ["password"]=> string(0) "" 
	       ["db_name"]=> string(8) "emoishop" 
               ["charset"]=> string(4) "utf8" 
               ["remark"]=> array(2) { ["note"]=> string(24) "要注意密码的安全" 
		 			       ["author"]=> string(3) "Lok" } }