0

在我的 wordpress 模型中,我为用户提供了 meta_value,称为 ref_credit。Sandro 的元值如下所示:

174 1   ref_credit  a:2:{i:0;s:1:"9";i:1;s:2:"10";}

意味着他推荐了 id=9,10 的用户

另一个用户 meta_value 如下所示:

209 9   ref_credit  a:1:{i:0;s:2:"11";}

他只提到了 1 个用户 id=11。

现在我想创建一个简单的排行榜,我模拟了一些东西,但逻辑完全错误。我了解我的代码以此比较值和顺序。我想按推荐的用户数量订购。

有任何想法吗?

完整的功能是这样的:

    //get_users calls WP_User_Query and returns an array of matching users
    $users = get_users(

        array(  'fields' => 'all_with_meta',
                'meta_query' => array( array( 'key' => 'ref_credit', // the meta field (or key) we want to target
                                              'compare' => '>='  // comparison method (optional:  =, >, <, etc)
        )))
    );

            //custom function for comparing the data we want to sort by
            function cmp($a, $b){
              if ($a->points == $b->points) {
                return 0;
              }
              return ($a->points > $b->points) ? -1 : 1;
            }

    //usort sorts our $users array with our function cmp()
    usort($users, 'cmp');

    //leaving an array of $users sorted by the value of meta 'points'
    echo '<ol>';
        foreach ($users as $user) {  
            echo '<li>' . $user->display_name . '</li>';
        }
    echo '</ol>';
4

1 回答 1

0

我认为有几个问题。

第一个是它all_with_meta似乎没有带回元数据,尽管顾名思义。不知道它应该做什么 -法典并没有多大帮助。因此,您必须自己获取这些ref_credit值。

其次,您的比较似乎使用了名为points,而不是ref_credit。不知道那是从哪里来的。由于ref_credit是一个数组,因此您必须比较数组长度,而不是值本身(使用countsay)。

保持原来的查询不变,这样的事情应该可以工作(尽管您可能必须检查我是否得到了cmp正确的结果):

//get_users calls WP_User_Query and returns an array of matching users
$users = get_users(
    array(  'fields' => 'all_with_meta',
            'meta_query' => array(
                array( 'key' => 'ref_credit', // the meta field (or key) we want to target
                    'compare' => '>='  // comparison method (optional:  =, >, <, etc)
                )
            )
        )
);

foreach($users as $user_id => $user) {
    $user->ref_credit = get_user_meta($user_id, 'ref_credit', true);
}

//custom function for comparing the data we want to sort by
function cmp($a, $b){
    return count($b->ref_credit) - count($a->ref_credit);
}

usort($users, 'cmp');

//leaving an array of $users sorted by the value of meta 'points'
echo '<ol>';
    foreach ($users as $user) {
        echo '<li>' . $user->display_name . '</li>';
    }
echo '</ol>';
于 2012-10-27T19:16:51.180 回答