我在 WP 中存储了一个 post_meta_key。该值是一个数组。
我做了一个 get_post_meta -第一次返回一个空数组。 $single
设置为假。这个数组被称为$voters
,因为它存储了一个选民列表。key 是用户 id,value 是一个数组,接下来介绍。
然后我遍历输入,清理它们,并创建另一个 key=>value 数组,称为current_vote
. 这是设置为用户 ID 键的值。
我想将current_vote
作为值插入到 voters 数组中。现在,我正在尝试这个:
$voters[$voter_id] = $current_vote;
这会正确地从 , 中创建一个键$voter_id
,并将current_vote
数组作为值。
但!随着第二次投票的到来,它不只是将另一个键插入现有数组 - 它接受第一次投票,并将其插入到一个新数组中!
第一次投票是这样的:
Array
(
[13] => Array
(
[13] => 0
[15] => 75
[21] => 0
[34] => 0
[16] => 0
[50] => 0
[28] => 0
[45] => 0
[10] => 0
[40] => 0
[41] => 0
[52] => 0
[22] => 0
[29] => 0
[23] => 0
[30] => 0
[48] => 0
[53] => 0
[38] => 0
[35] => 0
[61] => 0
[26] => 0
[9] => 0
[62] => 0
[54] => 0
[49] => 0
[14] => 0
[19] => 0
[42] => 0
[55] => 0
[5] => 0
[12] => 0
[46] => 0
[56] => 0
[32] => 0
[36] => 0
[2] => 0
[17] => 0
[4] => 0
[27] => 0
[44] => 0
[25] => 0
[57] => 0
[37] => 0
[3] => 0
[51] => 0
[31] => 0
[43] => 0
[47] => 0
[39] => 0
)
)
一旦第二次投票进来,它看起来像这样:
Array
(
[0] => Array
(
[13] => Array
(
[13] => 0
[15] => 75
[21] => 0
[34] => 0
[16] => 0
[50] => 0
[28] => 0
[45] => 0
[10] => 0
[40] => 0
[41] => 0
[52] => 0
[22] => 0
[29] => 0
[23] => 0
[30] => 0
[48] => 0
[53] => 0
[38] => 0
[35] => 0
[61] => 0
[26] => 0
[9] => 0
[62] => 0
[54] => 0
[49] => 0
[14] => 0
[19] => 0
[42] => 0
[55] => 0
[5] => 0
[12] => 0
[46] => 0
[56] => 0
[32] => 0
[36] => 0
[2] => 0
[17] => 0
[4] => 0
[27] => 0
[44] => 0
[25] => 0
[57] => 0
[37] => 0
[3] => 0
[51] => 0
[31] => 0
[43] => 0
[47] => 0
[39] => 0
)
)
[4] => Array
(
[13] => 75
[15] => 0
[21] => 0
[34] => 0
[16] => 0
[50] => 0
[28] => 0
[45] => 0
[10] => 0
[40] => 0
[41] => 0
[52] => 0
[22] => 0
[29] => 0
[23] => 0
[30] => 0
[48] => 0
[53] => 0
[38] => 0
[35] => 0
[61] => 0
[26] => 0
[9] => 0
[62] => 0
[54] => 0
[49] => 0
[14] => 0
[19] => 0
[42] => 0
[55] => 0
[5] => 0
[12] => 0
[46] => 0
[56] => 0
[32] => 0
[36] => 0
[2] => 0
[17] => 0
[4] => 0
[27] => 0
[44] => 0
[25] => 0
[57] => 0
[37] => 0
[3] => 0
[51] => 0
[31] => 0
[43] => 0
[47] => 0
[39] => 0
)
)
因此,元素被正确插入(新元素的键为 4),但第一个元素被插入到新的数组键 0 中。
这是我的完整代码:
$quarter = substr($date, 1,1);
$year = substr($date, 2,4);
$voters = get_post_meta(2165, 'bonus_votesq'. $quarter . $year);
//initialize vote arrays and vars
$votes = $_POST['votes'];
$voter_id = $_POST['voter_id'];
$voting_array = array();
$current_vote = array();
parse_str($votes, $voting_array);
foreach ($voting_array as $vid => $awarded_points) {
$current_vote[sanitize_key($vid)] = sanitize_key($awarded_points);
}
// push the local array into what will be the global array
$voters[$voter_id] = $current_vote;
//if meta_data doesn't exist, update_post_meta creates one. if it does, it updates it.
update_post_meta(2165,'bonus_votesq'. $quarter . $year, $voters);
echo print_r($voters);
到底是怎么回事?