如何将键值对添加到 wp post meta 中的数组?

How to add key value pairs to an array in wp post meta?

我正在为我的网站制作评级系统,我想将用户 ID 和评级值作为键值对存储在数组中,该数组存储为 post 元数据。

我的问题是我想出的代码采用了先前存储的数组,将其推送到子数组,然后添加了我的新键值对。然后,当下一个评分出现时,整个数组再次成为一个子数组,并添加新的键值对。

    // 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
)

或者创建一个单独的 table 并将评分存储在那里会更好吗?

只需要将get_post_meta()的第三个参数改成true:

$star_ratings = get_post_meta( $post_id, 'star_ratings', true );

好像不合逻辑,但是看到this discussion。我测试过这在 WP 4.4 中有效。