Unserialize Custom Field & Save as Multiple Rows in Wordpress Database

I have a custom field in post_meta table of wordpress database. It's called 'combined'. I want to seperate the values based on key and save them as multiple rows if there are multiple values for the key.

My meta_key:

Result after I run my code:

What I want:

My code:

add_action( 'init', function() {
    if ( 'migrate' !== filter_input( INPUT_GET, 'action' ) ) {
        return;
    }
 
    $query = new WP_Query( [
        'no_found_rows' = true,
        'update_post_term_cache' = false,
        'fields' = 'ids',
        'posts_per_page' = -1,
        'post_type'      = 'post',
        'post_status'    = 'any',
    ] );
    if ( ! $query-have_posts() ) {
        return;
    }
 
    while ( $query-have_posts() ) {
        $query-the_post();
        
        $data = get_post_meta( get_the_ID(), 'combined', true );
        
foreach($data as $singleData = $value ){
    
    update_post_meta( get_the_ID(), $singleData, $value );


}

    }
} );

Topic php database Wordpress

Category Web


I have found the way to get the values as I want them to be in the database. Changing the loop part in the above code with code did the trick.

$data = get_post_meta( get_the_ID(), 'combined', true );
        
foreach($data as $singleData => $value ){
    $thisArray = $data[$singleData];    
        foreach ($thisArray as $key2 => $value){
            add_post_meta( get_the_ID(), $singleData, $thisArray[$key2], $unique = false);
        }   
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.