WordPress用户元数据hca_recent数组合并异常问题求助
解决WordPress用户元数据数组合并后索引异常问题
问题背景
创建了名为hca_recent的用户元数据,首次通过Ajax存入单个关联数组时格式正常,但第二次调用Ajax合并旧数据时,使用get_user_meta(get_current_user_id(), 'hca_recent', false)获取的旧数据被包裹在[0]索引中,与新数组合并后出现格式混乱:旧数据在[0]索引,新数据直接以关联键展示,无法得到[0]、[1]、[2]这样的有序索引数组。
问题根源
get_user_meta函数的第三个参数设为false时,返回的是包含元数据值的二维数组(即使只有一条数据,也会被包装在[0]索引内)。而首次存入的是单个关联数组,合并时array_merge会将二维数组的[0]元素保留,同时把新关联数组的键直接追加到结果中,导致格式异常。
解决方案
需要将旧数据转换为有序索引数组,再将新的关联数组作为新元素追加到数组末尾,而非直接使用array_merge。以下提供两种可行方案:
方案1:使用get_user_meta的$single=true参数(推荐)
直接获取单个元数据值,避免二维数组的嵌套问题:
// 构造新的关联数组(与原代码一致) $hca_recent_array = array( 'recent_count' => $new_recent_count, 'post_id' => $post_id, 'video_id' => get_post_meta($post_id, "__cvm_video_id", true), 'post_title' => $_REQUEST['post_title'], 'video_url' => $_REQUEST['data_url'], ); // 获取旧数据,$single=true直接返回单个值,首次调用时为空 $hca_recent_array_old = get_user_meta(get_current_user_id(), 'hca_recent', true); // 初始化有序索引数组:如果旧数据是合法数组则复用,否则为空数组 $recent_list = is_array($hca_recent_array_old) ? $hca_recent_array_old : []; // 将新数组作为新元素追加到有序数组末尾 $recent_list[] = $hca_recent_array; // 更新用户元数据 $hca_recent = update_user_meta(get_current_user_id(), "hca_recent", $recent_list);
方案2:处理get_user_meta返回的二维数组
如果必须使用$single=false,则需要手动提取二维数组中的元素:
// 构造新的关联数组(与原代码一致) $hca_recent_array = array( 'recent_count' => $new_recent_count, 'post_id' => $post_id, 'video_id' => get_post_meta($post_id, "__cvm_video_id", true), 'post_title' => $_REQUEST['post_title'], 'video_url' => $_REQUEST['data_url'], ); // 获取旧数据,$single=false返回二维数组 $hca_recent_array_old = get_user_meta(get_current_user_id(), 'hca_recent', false); // 初始化有序索引数组 $recent_list = []; // 遍历旧数据,提取有效元素到有序数组 if (!empty($hca_recent_array_old) && is_array($hca_recent_array_old)) { foreach ($hca_recent_array_old as $item) { if (is_array($item)) { $recent_list[] = $item; } } } // 追加新元素 $recent_list[] = $hca_recent_array; // 更新用户元数据 $hca_recent = update_user_meta(get_current_user_id(), "hca_recent", $recent_list);
验证结果
执行修正后的代码后,用户元数据将得到期望的有序索引数组:
Array ( [0] => Array ( [recent_count] => 42 [post_id] => 667 [video_id] => 881950864 [post_title] => Receiver Blocking: COD + Dots Drill | Tee Martin [video_url] => https://player.vimeo.com/video/881950864?h=e9b41820da&autoplay=0&muted=0&loop=0&title=1&byline=1&portrait=1&color&dnt=0&background=0&transparent=0 ) [1] => Array ( [recent_count] => 43 [post_id] => 695 [video_id] => 881950748 [post_title] => Tee Martin | Youth Coaching Keys to Success [video_url] => https://player.vimeo.com/video/881950748?h=d3b0944767&autoplay=0&muted=0&loop=0&title=1&byline=1&portrait=1&color&dnt=0&background=0&transparent=0 ) )
内容的提问来源于stack exchange,提问作者Jamie Gamauf
相关产品推荐
相关产品推荐

