简体   繁体   中英

How do I update serialized data in a MySQL database using PHP?

Here is a serialized data stored in MySQL database:

sizes_0#10_1$shape_0#20$bannertype_0#20$sizes_1#1_3$shape_1#20$

How do I remove sizes1 from the above data?

First you should de-serialize the data:

$string = 'sizes_0#10_1$shape_0#20$bannertype_0#20$sizes_1#1_3$shape_1#20$';

function custom_unserialize($string) {
    return array_map(function($token) {
        return explode('#', $token);
    }, explode('$', $string));
}

$data = custom_unserialize($string);

then you can remove the sizes1 entry:

$data_without_sizes_1 = array_filter($data, function($data) {
    return $data[0] !== 'sizes_1';
});

finally you can serialize the data again:

function custom_serialize(array $data) {
    return implode('$', array_map(function($entry) {
        return implode('#', $entry);
    }, $data));
}

$serialized_string = custom_serialize($data_without_sizes_1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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