按列值对数组进行排序

时间:2018-04-24 09:48:20

标签: php arrays wordpress sorting plugins

我正在使用我的简单wordpress插件。此插件应根据书面帖子的数量对所有用户进行排名,然后将其显示在html表格中。一切正常,除了排序。您有任何想法如何按Number_of_posts值对此数组进行排序吗?

for($id = 1;$id<=$total_users;$id++){

    $ar = $wpdb->get_results("SELECT wp_users.ID, wp_users.display_name, 
                                    COUNT(wp_posts.post_author) AS 'Number_of_posts' 
                            FROM wp_users 
                                INNER JOIN wp_posts ON wp_users.ID = wp_posts.post_author 
                            WHERE  wp_posts.post_type = 'post'  
                            AND wp_users.ID = $id 
                            AND wp_posts.post_status = 'publish'" ,         
                            ARRAY_A);


    function sort($a, $b) {
        return $a['Number_of_posts'] - $b['Number_of_posts'];
    }

    usort($ar, 'sort');

    foreach ($ar as $x){
        echo'<tr>'; 

        echo'<td>'. $x['ID']."</td>";
        echo'<td>'. $x['display_name'].'</td>';
        echo'<td>'. $x['Number_of_posts'].'</td>';
        echo'</tr>';
    }
}

echo '</table>';
echo '<br>';

1 个答案:

答案 0 :(得分:0)

试试此代码

function my_count_posts_by_user(){

    global $wpdb; 
    $result = count_users();
    $total_users = $result['total_users'];

    for($id = 1;$id<=$total_users;$id++){

        $ar = $wpdb->get_results("SELECT wp_users.ID, wp_users.display_name, 
                                COUNT(wp_posts.post_author) AS 'Number_of_posts' 
                        FROM wp_users 
                            INNER JOIN wp_posts ON wp_users.ID = wp_posts.post_author 
                        WHERE  wp_posts.post_type = 'post'  
                        AND wp_users.ID = $id 
                        AND wp_posts.post_status = 'publish' order by  Number_of_posts desc" ,         
                        ARRAY_A);

        //usort($ar, 'sort');
        echo '<table>';
        foreach ($ar as $x){
            echo'<tr>'; 

            echo'<td>'. $x['ID']."</td>";
            echo'<td>'. $x['display_name'].'</td>';
            echo'<td>'. $x['Number_of_posts'].'</td>';
            echo'</tr>';
        }
    }

    echo '</table>';
    echo '<br>';
}