在 PHP 中从序列化数组中获取一个值
您认为从数组中获取单个值的最有效方法是什么。我知道它是什么,我知道它在哪里。目前我正在这样做:
$array = unserialize($storedArray);
$var = $array['keyOne'];
想知道是否有更好的方法。
What would you say is the most efficient way to get a single value out of an Array. I know what it is, I know where it is. Currently I'm doing it with:
$array = unserialize($storedArray);
$var = $array['keyOne'];
Wondering if there is a better way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
你做得很好,我想不出比你所做的更好的方法了。
这就是它可以完成的方式。
You are doing it fine, I can't think of a better way than what you are doing.
That's the way it can be done.
对于您给出的数组示例,我认为您没问题。
如果序列化字符串包含您不想反序列化的数据和对象(例如创建您确实不想拥有的对象),您可以使用 序列化 PHP 库,它是序列化数据的完整解析器。
它提供对序列化数据的静态低级访问,因此您只能提取数据的子集和/或操作序列化数据而不对其进行反序列化。然而,对于您的示例来说,这看起来太多了,因为您只有一个数组,而且我猜您不需要过滤/差异太多。
For the example you give with the array, I think you're fine.
If the serialized string contains data and objects you don't want to unserialize (e.g. creating objects you really don't want to have), you can use the Serialized PHP library which is a complete parser for serialized data.
It offers low-level access to serialized data statically, so you can only extract a subset of data and/or manipulate the serialized data w/o unserializing it. However that looks too much for your example as you only have an array and you don't need to filter/differ too much I guess.
这是您可以执行的最有效的方法,反序列化并获取数据,如果您需要优化,请不要存储所有序列化的变量。
而且总有办法用正则表达式来解析它:)
Its most efficient way you can do, unserialize and get data, if you need optimize dont store all variables serialized.
Also there is always way to parse it with regexp :)
如果您不想取消整个事物的序列化(这可能会很昂贵,尤其是对于更复杂的对象),您可以只执行 strpos 并查找您想要的特征并提取它们
If you dont want to unseralize the whole thing (which can be costly, especially for more complex objects), you can just do a strpos and look for the features you want and extract them
当然。
如果您需要更好的方法 - 不要使用序列化数组。
序列化只是一种传输格式,用途非常有限。
如果您需要一些优化的变体 - 有数百个。
例如,您可以传递一些单个标量变量而不是整个数组。并立即访问
Sure.
If you need a better way - DO NOT USE serialized arrays.
Serialization is just a transport format, of VERY limited use.
If you need some optimized variant - there are hundreds of them.
For example, you can pass some single scalar variable instead of whole array. And access it immediately
我也认为正确的方法是取消序列化。
但另一种方法可能是使用字符串操作,当你知道你想从数组中得到什么时:
现在,有人准备进行基准测试吗? ;)
另一种方式可能是RegEx?
I, too, think the right way is to un-serialize.
But another way could be to use string operations, when you know what you want from the array:
Now, someone up for a benchmark? ;)
Another way might be RegEx ?