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条回答

    报告相同问题?

    悬赏问题

    • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
    • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
    • ¥30 python代码,帮调试
    • ¥15 #MATLAB仿真#车辆换道路径规划
    • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
    • ¥15 数据可视化Python
    • ¥15 要给毕业设计添加扫码登录的功能!!有偿
    • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
    • ¥15 微信公众号自制会员卡没有收款渠道啊
    • ¥100 Jenkins自动化部署—悬赏100元