我在post meta中更新数组时遇到问题。数组保持覆盖而不是推入新值。
add_action('wp_ajax_update_item_received', 'update_item_received');
function update_item_received() {
$date = date('Y/m/d H:i');
$order_id = $_POST['order_id'];
$item_id = $_POST['item_id'];
$received_array = get_post_meta($order_id,"received_array");
if(is_array($received_array[0])) {
//merge new with old
$received_array_2[$item_id] = $date;
array_merge($received_array[0],$received_array_2);
update_post_meta($order_id,"received_array",$received_array);
} else {
$received_array = array("$item_id"=>"$date");
add_post_meta($order_id,"received_array",$received_array);
}
我使用array_merge
但新数组与旧数组合并。它变成了一个多维数组?
我如何解决?
答案 0 :(得分:1)
get_post_meta()
函数默认将meta作为数组返回。如果您知道您将始终只有一个,请使用第三个参数true
,这意味着它将只返回一个元项目。
然后你可以添加它:
function update_item_received() {
$date = date('Y/m/d H:i');
$order_id = $_POST['order_id'];
$item_id = $_POST['item_id'];
$received_array = get_post_meta($order_id, "received_array", true);
if(is_array($received_array)) {
$received_array[$item_id] = $date;
update_post_meta($order_id, "received_array", $received_array);
} else {
$received_array = array("$item_id"=>"$date");
add_post_meta($order_id, "received_array", $received_array);
}
}