dsn1327 2016-12-30 15:08
浏览 38

使用MySQL SELECT查询(Wordpress)重新格式化MySQL数据库表中的JSON数组

I have a Wordpress build that uses CalderaWP forms. Unfortunately, the plugin's author has decided to store all checkbox entries as JSON arrays in the WP database and custom field values show up as "Array" instead of the actual text values.

I'd like to run a cron job that reformats these entries, but the first part is trying to figure out how to find and replace all values that are JSON objects.

I've written a function to get values from a specific table in the database, specifically the "wp_cf_form_entry_values" table. This function uses a regular expression in the SELECT query to find all values that begin with the "{" character. This is what I came up with to find JSON objects in the value field, but maybe there is a better way. Anyway, the function gets these values and reformats them from a JSON object to a list of individual items (i.e. various values that were checked in the submitted form).

Here is my current function:

function reformat_my_data() {
    global $wpdb;
    $data = $wpdb->get_results("SELECT value 
                                FROM `wp_cf_form_entry_values` 
                                WHERE `value` REGEXP '^[{].*$'
                                ");

    foreach($data as $key => $field) {

        foreach($field as $val) {
            if( is_json($val) ) {
                $val = json_decode($val, true);

                foreach($val as $checked) {
                    echo ' - ' . $checked . '<br/>';
                }
            }
        }

    }

}
reformat_my_data();

I also have another function to determine if the value is a JSON object:
function is_json($string) { json_decode($string); return (json_last_error() == JSON_ERROR_NONE); }

This works and outputs a list like this:
- checked #1
- checked #2
- checked #3

My question is: How do I get this newly formatted value back into the database? In other words, how do I do a mass replace of JSON type objects in the WP database?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥30 这是哪个作者做的宝宝起名网站
    • ¥60 版本过低apk如何修改可以兼容新的安卓系统
    • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
    • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
    • ¥50 有数据,怎么用matlab求全要素生产率
    • ¥15 TI的insta-spin例程
    • ¥15 完成下列问题完成下列问题
    • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
    • ¥15 YoloV5 第三方库的版本对照问题
    • ¥15 请完成下列相关问题!