我希望使用Ajax删除密钥[1]
从存储在自定义用户字段中的以下数组中,然后重新保存它。。。
我试图通过使用unset($array[$key])
然后保存更新的值,但恐怕没有成功。
谢谢你的帮助。。。
Array (
[0] => Array (
[dna_cal_when] => 1576926000
[dna_cal_position_id] =>
[dna_cal_candidate_id] =>
)
[1] => Array (
[dna_cal_when] => 1576927800
[dna_cal_position_id] =>
[dna_cal_candidate_id] =>
)
[2] => Array (
[dna_cal_when] => 1576929600
[dna_cal_position_id] =>
[dna_cal_candidate_id] =>
)
)
Here is the function...
add_action( \'wp_ajax_dna_nuke_diary_slots\', \'dna_nuke_diary_slots\' );
function dna_nuke_diary_slots() {
$user = $_POST[\'user\'];
$stamp = array($_POST[\'stamp\']);
// values for these two variables are retrieved from custom data attribute in following html and ajax call
$stamps = !empty(get_user_meta( $user, \'dna_cal\', true)) ? get_user_meta( $user, \'dna_cal\', true) : array();
$key = array_search($stamp, array_column($stamps, \'dna_cal_when\'));
unset($stamps[$key]);
$new_stamps = $stamps;
$sort_stamps = array_values($new_stamps);
update_user_meta( $user, \'dna_cal\', $sort_stamps);
wp_die();
}
FYI - following is the Ajax call and a sample of the HTML
$(\'.slot\').on(\'click\', \'a.booked\', function(e) {
e.preventDefault();
var user = $(\'#dna_day\').attr( \'data-user\' );
var stamp = $(this).attr( \'data-timestamp\' );
$(this).removeClass(\'booked\').addClass(\'nuked\');
$.ajax({
type: \'POST\',
url: ajax_object.ajaxurl,
data: {
action: \'dna_nuke_diary_slots\',
user: user,
stamp: stamp
}
});
});
<div id="dna_day" class="dna-day" data-user="256">
<div id="dna_slots" class="slots">
<div class="slot"><a class="booked" data-timestamp="1576926000" href="#"></a></div>
<div class="slot"><a class="booked" data-timestamp="1576927800" href="#"></a></div>
<div class="slot"><a class="booked" data-timestamp="1576929600" href="#"></a></div>
</div>
</div>
最合适的回答,由SO网友:Chetan Vaghela 整理而成
当前无法取消设置密钥,因为无法从数组中找到正确的密钥。问题是你做到了$stamp = array($_POST[\'stamp\']);
作为错误的数组。您必须删除array()
从…起$stamp
, 所以看起来像$stamp = $_POST[\'stamp\'];
. 然后,您可以从数组中搜索列中的值并将其取消设置。我已经测试了以下正常工作的代码。
add_action( \'wp_ajax_dna_nuke_diary_slots\', \'dna_nuke_diary_slots\' );
function dna_nuke_diary_slots() {
$user = $_POST[\'user\'];
$stamp = $_POST[\'stamp\']; // here you have to remove array();
// values for these two variables are retrieved from custom data attribute in following html and ajax call
$stamps = !empty(get_user_meta( $user, \'dna_cal\', true)) ? get_user_meta( $user, \'dna_cal\', true) : array();
$key = array_search($stamp, array_column($stamps, \'dna_cal_when\'));
unset($stamps[$key]);
$new_stamps = $stamps;
$sort_stamps = array_values($new_stamps);
update_user_meta( $user, \'dna_cal\', $sort_stamps);
wp_die();
}