【发布时间】:2016-04-06 00:44:41
【问题描述】:
我正在为我的网站制作评分系统,我想将用户 ID 和评分值作为键值对存储在数组中,并存储为帖子元数据。
我的问题是我想出的代码采用先前存储的数组,将其推送到子数组,然后添加我的新键值对。然后当下一个评分进来时,整个数组再次变成一个子数组,并添加新的键值对。
// Get post meta
$star_ratings = get_post_meta( $post_id, 'star_ratings', false );
$star_rating_key = get_current_user_id();
$star_rating_value = $rating;
$star_ratings[$star_rating_key] = $star_rating_value;
// Debug
debug_to_console( print_r($star_ratings ) );
// If we fail to update the post meta, respond with -1; otherwise, respond with 1.
echo false == update_post_meta( $post_id, 'star_ratings', $star_ratings ) ? "-1" : "1";
这是我从调试中获得第一个评级后得到的结果:
Array
(
[1] => 5
)
这是第二次评分后的样子:
Array
(
[0] => Array
(
[1] => 5
)
[19] => 3
)
我做错了什么或者我应该怎么做? 我想拥有它:
Array (
[1] => 5,
[19] => 3
)
或者创建一个单独的表并将评分存储在那里会更好吗?
【问题讨论】:
标签: php arrays wordpress associative-array