gpt4 book ai didi

php - 将值添加到数组中的用户元字段

转载 作者:搜寻专家 更新时间:2023-10-31 20:36:24 25 4
gpt4 key购买 nike

我想为用户元字段添加以下数据库条目:

meta_key => array ('value 1', 'value 2', 'value 3')

我尝试通过第一次推送创建用户元字段:

update_user_meta(
$user->id,
meta_key,
array ($value1)
);

现在我想向数组中添加新值。但我不想失去第一。这怎么可能?add_user_meta 不起作用,因为它一直在添加新的数据库条目。

最佳答案

你分享的代码有点神秘,但我会尽力给你答案。

从概念上讲,您只想先获取元数据,更新它,然后重写它。

所以,一旦你的元值被写入,当你想要更新时,你会做这样的事情:

// Lets create a reusable function for simplicity
/*
* @param int $user id
* @param string $meta_key
* @param string $new_value - the new value to be added to the array
*/
function my_meta_update($user_id, $meta_key, $new_value) {
// Get the existing meta for 'meta_key'
$meta = get_user_meta($user_id, $meta_key, false);
// Do some defensive coding - if it's not an array, set it up
if ( ! array($meta) ) {
$meta = array();
}
// Push a new value onto the array
$meta[] = $new_value;
// Write the user meta record with the new value in it
update_user_meta($user_id, $meta_key, $meta);
}

然后您可以像这样使用该函数更新用户元数据:

// Add the "Value 2" to the array of meta values for user 1
my_meta_update(1, 'my_meta_key', 'Value 2');

奖金
应 OP 的要求,这里有一个删除值的方法:

/**
* @param int $user_id
* @param string $meta_key
* @param string $remove_value - the value to remove from the array
*/
function my_meta_remove($user_id, $meta_key, $remove_value) {
$meta = get_user_meta($user_id, $meta_key, false);
// Find the index of the value to remove, if it exists
$index = array_search($remove_value, $meta);
// If an index was found, then remove the value
if ($index !== FALSE) {
unset($meta[$index]);
}
// Write the user meta record with the removed value
update_user_meta($user_id, $meta_key, $meta);
}

用法:

// Remove "Value 2" from the array of meta values for user 1
my_meta_remove(1, 'my_meta_key', 'Value 2');

关于php - 将值添加到数组中的用户元字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34001707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com