将整个 PHP 数组散列为唯一值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5097632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hashing an entire PHP array into a unique value
提问by loneboat
Looking for a way to produce a filename-safe hash of a given PHP array. I'm currently doing:
寻找一种方法来生成给定 PHP 数组的文件名安全哈希。我目前正在做:
$filename = md5(print_r($someArray, true));
... but it feels "hacky" using print_r() to generate a string unique to each array.
...但使用 print_r() 生成每个数组唯一的字符串感觉很“hacky”。
Any bright ideas for a cleaner way to do this?
对于更清洁的方式来做到这一点有什么好主意吗?
EDITWell, seems everyone thinks serialize is better suited to the task. Any reason why? I'm not worried about ever retrieving information about the variable after it's hashed (which is good, since it's a one-way hash!). Thanks for the replies!
编辑好吧,似乎每个人都认为序列化更适合这项任务。有什么理由吗?我不担心在散列后检索有关变量的信息(这很好,因为它是单向散列!)。感谢您的回复!
回答by Michael Berkowski
Use md5(serialize())
instead of print_r()
.
使用md5(serialize())
代替print_r()
。
print_r()
's purpose is primarily as a debugging function and is formatted for plain text display, whereas serialize()
encodes an array or object representation as a compact text string for persistance in database or session storage (or any other persistance mechanism).
print_r()
的目的主要是作为调试功能并格式化为纯文本显示,而serialize()
将数组或对象表示编码为紧凑的文本字符串,以便在数据库或会话存储(或任何其他持久性机制)中持久化。
回答by generalhenry
Alternatively you could use json_encode
或者你可以使用json_encode
回答by Pekka
serialize()
should work fine.
serialize()
应该工作正常。
It has the additional advantage of invoking the __sleep
magic method on objects, and being the cleanest serialization method available in PHP overall.
它具有__sleep
在对象上调用魔法方法的额外优势,并且是 PHP 中可用的最干净的序列化方法。
回答by Damp
What about serialize?
序列化呢?
$filename = md5(serialize($someArray));
$filename = md5(serialize($someArray));
回答by greg0ire
Using serialize()
might be more conservative if you want to keep the type, etc...
serialize()
如果您想保留类型等,使用可能会更保守...