【问题标题】:How to add key value pairs to an array in wp post meta?如何将键值对添加到 wp post meta 中的数组?
【发布时间】: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


    【解决方案1】:

    你只需要把get_post_meta()的第三个参数改成true

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

    这似乎不合逻辑,但请参阅this discussion。我测试了这在 WP 4.4 中有效。

    【讨论】:

    • 哇,谢谢。这似乎真的不合逻辑。没想到会有解决方案:)
    猜你喜欢
    • 2018-04-07
    • 2021-03-07
    • 2018-05-24
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 2016-07-22
    • 2014-01-10
    相关资源
    最近更新 更多