【问题标题】:Updating MySQL Field that is array更新数组的 MySQL 字段
【发布时间】:2014-11-23 13:52:18
【问题描述】:

我使用 json_encode 将数据作为数组存储在我的一个数据库字段中。数据按预期存储,一旦我使用

运行 json_decode,我就可以检索和查询数组
if ( array_key_exists( 'my_key', json_decode( $mydb->field ) ) ) ...

我现在要做的是通过添加一个额外的 $key => $value 来更新这个数组,但我一辈子都想不通!

我目前正在使用...

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 ) );

它将新值作为数组插入,但覆盖了以前的值而不是添加到它。

感谢任何提示!

【问题讨论】:

    标签: php mysql arrays json wordpress


    【解决方案1】:

    查看PHP函数json_decode的定义:

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

    在您的情况下,您必须使用 TRUE 的第二个参数,因为您将解码的 JSON 作为关联数组而不是 PHP 对象处理。

    特别是,您的行: if( !is_array( $cron_update ) ) $cron_update = array();

    当你不使用json_decode( $event->cronned, TRUE );时会一直执行

    希望这会有所帮助。

    加布里埃尔

    【讨论】:

    • 不敢相信我错过了...显然盯着它太久了!谢谢!
    猜你喜欢
    • 2023-01-07
    • 1970-01-01
    • 2012-10-04
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    相关资源
    最近更新 更多