简体   繁体   English

PHP更新序列化数据

[英]PHP Update Serialized Data

I need some help with unserializing and updating the array values and reserializing them (using php). 我需要一些帮助来反序列化和更新数组值并重新序列化它们(使用php)。 Basically I want to be able to unserialize a string, update the value for a specific key (without loosing the other values) and reserialize it. 基本上我希望能够反序列化字符串,更新特定键的值(不丢失其他值)并重新序列化它。 I've searched and can't seem to find a viable solution (or maybe I'm just typhlotic). 我已经搜索过,似乎无法找到可行的解决方案(或者我可能只是一种性格问题)。

The array I'm trying to update is very simple. 我正在尝试更新的数组非常简单。 It has a key and value. 它具有关键和价值。

array (
    'key' => 'value',
    'key2' => 'value2',
)

I currently have, but it does not work. 我目前有,但它不起作用。

foreach(unserialize($serializedData) as $key => $val)
{
    if($key == 'key')
    {
        $serializedData[$key] = 'newValue';
    }
}

$updated_status = serialize($serializedData);

You can't write directly to the serialized data string like you are trying to do here: 您不能像在这里尝试那样直接写入序列化数据字符串:

$serializedData[$key] = 'newValue';

You need to deserialize the data to an array, update the array, and then serialize it again. 您需要将数据反序列化为数组,更新阵列,然后再次序列化。 It seems as if you only want to update the value if the key exists, so you can do it like this: 如果密钥存在,似乎您只想更新值,所以您可以这样做:

$data = unserialize($serializedData);
if(array_key_exists('key', $data)) {
    $data['key'] = 'New Value';
}
$serializedData = serialize($data);

Exactly, how you described it: Unserialize, update, serialize. 确切地说,您是如何描述它的:反序列化,更新,序列化。

$data = unserialize($serializedData);
$data['key'] = 'newValue';
$updated_status = serialize($data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM