Getting one value out of a serialized array in PHP

大城市里の小女人 提交于 2019-12-23 17:50:30

问题


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.


回答1:


You are doing it fine, I can't think of a better way than what you are doing.

  • You unserialize
  • You get an array
  • You get value by specifying index

That's the way it can be done.




回答2:


Wondering if there is a better way.

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.




回答3:


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 :)




回答4:


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




回答5:


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




回答6:


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:

$storedArray = 'a:2:{s:4:"test";s:2:"ja";s:6:"keyOne";i:5;}';
# another: a:2:{s:4:"test";s:2:"ja";s:6:"keyOne";s:3:"sdf";}
$split = explode('keyOne', $storedArray, 2);
# $split[1] contains the value and junk before and after the value
$splitagain = explode(';', $split[1], 3);
# $splitagain[1] should be the value with type information
$value = array_pop(explode(':', $splitagain[1], 3));
# $value contains the value

Now, someone up for a benchmark? ;) Another way might be RegEx ?



来源:https://stackoverflow.com/questions/8192789/getting-one-value-out-of-a-serialized-array-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!