【问题标题】:Getting a single MYSQL result where the field is an array获取字段为数组的单个 MYSQL 结果
【发布时间】:2015-01-24 22:37:00
【问题描述】:

Wordpress 数据库,这个有点卡住了。

我正在使用以下内容来获取当前用户的 ID。

 $user_ID = get_current_user_id();

这会返回如下内容:

 15

现在我尝试在 show_user_list 字段中查找 $user_ID 的匹配值,该字段中的数据存储在一个数组中。

看起来像这样:

 a:2:{i:0;s:2:"29";i:1;s:2:"15";}

这是我正在运行的查询(连同一组条件):

global $wpdb; $result = $wpdb->get_results( "SELECT post_id FROM wp_postmeta WHERE show_user_list IN (' . implode(',', $user_ID) . ' AND post_type = 'show' AND post_status = 'publish'" );

然后我试图用这个来呼应匹配 post_id 的值:

 foreach ( $result as $unique ) {
 echo $unique->post_id;
 }

但它没有返回任何东西。我知道我在处理数组时一定犯了一个错误,但我不知道我哪里出错了?

【问题讨论】:

    标签: php mysql arrays wordpress


    【解决方案1】:

    看起来您已经在 show_user_list 字段中存储了一个序列化数组,因此使用 db 查询搜索值会很麻烦。

    在您描述的模型中,您必须从 wp_postmeta 中选择匹配“post_type = 'show' AND post_status = 'publish'”的所有行,然后手动过滤未序列化的 show_user_list 字段中没有用户 ID 的结果.

    您可以尝试以下方法: in_array($user_ID, unserialize($row->show_user_list))

    另外,我注意到您的查询中有多个错误:字符串未正确连接 PHP 代码并且 IN 子句的右括号未关闭。

    问候, 一样的

    编辑

    提供您提供的信息,我将如何解决您的问题:

    $user_ID = get_current_user_id();
    global $wpdb;
    $results = $wpdb->get_results("SELECT post_id, show_user_list FROM wp_postmeta WHERE post_type = 'show' AND post_status = 'publish'");
    $user_post_ids = array();
    foreach ($results as $post) {
        if (in_array($user_ID, unserialize($post->show_user_list))) {
            $user_post_ids[] = $post->post_id;
        }
    }
    

    希望这会有所帮助!

    【讨论】:

    • 感谢您的帮助 同样。我真的不知道如何实施您的建议。您能提供的任何建议都会很棒。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-19
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    相关资源
    最近更新 更多