update_post_meta() updating nested array in Multidimensional array with empty sub-array

How can i update/remove/empty a sub-array on user post submission in admin area?

here ist the reference on how to update nested array i am using but it is not working

if ( $post-post_type == 'ds_product' ) {
     
    
    if ( isset( $_POST['meta'] ) ) { 
        if ( !empty($_POST['meta']['ds_product_gallery']) ){
             
            $gallery_data = []; 

            for ($i = 0; $i  count( $_POST['meta']['ds_product_gallery']['picture'] ); $i++ )
            {
                if ( !empty($_POST['meta']['ds_product_gallery']['picture'][ $i ]))
                {
                    $gallery_data['picture'][ ]    = $_POST['meta']['ds_product_gallery']['picture'][ $i ];
                    $gallery_data['figcaption'][ ] = $_POST['meta']['ds_product_gallery']['figcaption'][ $i ];
                }
            }

            if ( !empty($gallery_data) ) {
                $_POST['meta']['ds_product_gallery'] = $gallery_data;
            } 
        
        }else{  
            // this section doesn't clear the array
            $data = get_post_meta( $post-ID, 'meta', true );  
            $data['ds_product_gallery'][0][0] = [];
            update_post_meta( $post_ID, 'meta', $data[0] ); 
            
        } 
        foreach( $_POST['meta'] as $key = $value ){
            update_post_meta( $post_id, $key, $value );
        }
    } 
}

Topic array post-meta Wordpress

Category Web


You would do it the same way as any other PHP application, this isn't a WordPress problem.

To remove an item from an array in PHP, use unset( thing to remove ).

E.g.

$test = [ 'banana', 'cucumber', 'apple' ];
unset( $test[1] );
// cucumber is no longer in the test array, and the array now has 2 not 3 items

About

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