PHP头条
热点:

你可能会注意到,尽管字符串是唯一的,前几个字符却是类似的,这是因为生成的字符串与服务器时间相关。但实际上也存在友好的一方面,由于每个新生成的 ID 会按字母顺序排列,这样排序就变得很简单。为了减少重复的概率,你可以传递一个前缀,或第二个参数来增加熵:

以下为引用的内容:

// with prefix
echo uniqid('foo_');
/* prints
foo_4bd67d6cd8b8f
*/

// with more entropy
echo uniqid('',true);
/* prints
4bd67d6cd8b926.12135106
*/

// both
echo uniqid('bar_',true);
/* prints
bar_4bd67da367b650.43684647
*/

这个函数将产生比 md5() 更短的字符串,能节省一些空间。

7、序列化

你有没有遇到过需要在数据库或文本文件存储一个复杂变量的情况?你可能没能想出一个格式化字符串并转换成数组或对象的好方法,PHP 已经为你准备好此功能。有两种序列化变量的流行方法。下面是一个例子,使用 serialize() 和 unserialize() 函数:

以下为引用的内容:

// a complex array
$myvar = array(
 'hello',
 42,
 array(1,'two'),
 'apple'
);

// convert to a string
$string = serialize($myvar);

echo $string;
/* prints
a:4:{i:0;s:5:"hello";i:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3:"two";}i:3;s:5:"apple";}
*/

// you can reproduce the original variable
$newvar = unserialize($string);

print_r($newvar);
/* prints
Array
(
    [0] => hello
    [1] => 42
    [2] => Array
        (
            [0] => 1
            [1] => two
        )

    [3] => apple
)
*/

这是原生的 PHP 序列化方法。然而,由于 JSON 近年来大受欢迎,3lian素材,PHP5.2 中已经加入了对 JSON 格式的支持。现在你可以使用 json_encode() 和 json_decode() 函数:

以下为引用的内容:

// a complex array
$myvar = array(
 'hello',
 42,
 array(1,'two'),
 'apple'
);

// convert to a string
$string = json_encode($myvar);

echo $string;
/* prints
["hello",42,[1,"two"],"apple"]
*/

// you can reproduce the original variable
$newvar = json_decode($string);

print_r($newvar);
/* prints
Array
(
    [0] => hello
    [1] => 42
    [2] => Array
        (
            [0] => 1
            [1] => two
        )

    [3] => apple
)
*/

这将更为行之有效,尤其与 JavaScript 等许多其他语言兼容。然而对于复杂的对象,某些信息可能会丢失。

www.phpzy.comtrue/php/711.htmlTechArticle你可能会注意到,尽管字符串是唯一的,前几个字符却是类似的,这是因为生成的字符串与服务器时间相关。但实际上也存在友好的一方面,由于每个新生...

相关文章

    暂无相关文章
相关频道:

PHP之友评论

今天推荐