dqnf28092 2015-03-26 15:16
浏览 9
已采纳

订购Foreach循环结果

I cannot use the 'orderby' => 'post_count' as contributors have multiple posts assigned to them.

Rather, for each user output, I get their $post_count using the count_user_posts() function.

How can I re-order the items based on this number? Highest to lowest?

The user post count is not part of the $users array :(

            // order contributors
            $args = array(
                'role' => contributors,
                'orderby' => 'post_count',
                'order' => 'ASC',
                'fields' => 'all'
            );

            // The Query
            $user_query = new WP_User_Query( $args );
            $users = $user_query->get_results();

            echo '<ul>';
            $i = 0;
            foreach ( $users as $user ) {

                $post_count = count_user_posts( $user->id );

                if ( count_user_posts( $user->id ) >= 1 ) {
                    echo '<li class="ws-sort" data-sort="' . $post_count . '"><a href="' . site_url() . '/author/' . $user->user_nicename . '">' . $user->display_name . '</li>';
                    if (++$i == 8) break;
                }
            }
            echo '</ul>';
  • 写回答

1条回答 默认 最新

  • doudao1837 2015-03-26 15:34
    关注

    You can use usort with a custom function:

    usort($users, function(&$a,&$b) {
        if (!isset($a->_post_count)) $a->_post_count = count_user_posts( $a->id );
        if (!isset($b->_post_count)) $b->_post_count = count_user_posts( $b->id );
        return  $a->_post_count < $b->_post_count;
    });
    

    And you can also use _post_count in the other foreach, since the sorting modified each element ( $a and $b are passed by reference )

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100