简体   繁体   中英

Updating MySQL Field that is array

I have data stored in one of my DB fields as an array using json_encode. The data is stored as expected and I can retrieve and query the array once I have ran json_decode by using

if ( array_key_exists( 'my_key', json_decode( $mydb->field ) ) ) ...

What I am now trying to do is update this array by adding an additional $key => $value but I can't for the life of me figure it out!

I am currently using...

if( $event->cronned != '' ) {
                        $cron_update = json_decode( $event->cronned );
                    }
                    if( !is_array( $cron_update ) ) $cron_update = array();
                    $cron_update[$mdjm_schedules['balance-reminder']['slug']] = time();
                    $update_args = array(
                                'last_updated_by' => '0',
                                'last_updated'  => date( 'Y-m-d H:i:s' ),
                                'cronned'        => json_encode( $cron_update ),
                                );
                    $update_enquiry = $wpdb->update( $db_tbl, $update_args, array( 'event_id' => $event->event_id ) );

It is inserting the new value as an array but over writing the previous values rather than adding to it.

Any tips appreciated!

Look at the definition for PHP function json_decode:

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

You must use the second parameter to TRUE in your case, because you are handling the decoded JSON as an associative array rather than a PHP object.

In particular, your line: if( !is_array( $cron_update ) ) $cron_update = array();

will execute all the time, when you don't use json_decode( $event->cronned, TRUE );

Hope this helps.

Gabriel

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