php脚本显示顺序

问题描述

我有这段代码可以在wordpress生成一个评级列表,我可以获取列表中每个公司的评级,但是我不能按降序排列列表,并且将帖子的数量限制为5。请问有什么建议吗?

 <?PHP
$reviews = apply_filters( 'glsr_get_reviews',[],[
    'order' => 'DESC','orderby' => 'Meta_value_key','post_status' => 'publish','post_type' => 'page',// change this as needed
    'posts_per_page' => 5,// change this as needed
]);

foreach( $reviews as $review ) {
    $reviewHtml = $review->build(); ?>
           
    <p><?PHP echo $reviewHtml->assigned_to; ?></p>
    <p><?PHP echo $reviewHtml->rating; ?></p>
    <?PHP echo '<br/>'; ?>
<?PHP wp_reset_postdata(); ?>
<?PHP } ?>

非常感谢

解决方法

由于要对数组进行降序排序并仅显示前五个元素,因此以下代码将为您完成此操作。但是我应该解释一下我的所作所为。

  1. 首先,我使用array_reverse()函数反转数组,该函数将按降序对数组元素进行排序。
  2. 然后我初始化了名为$limit的变量以限制要显示的元素数。
  3. 我在if循环中添加了条件foreach语句,以在达到$limit的最大值时脱离foreach循环。 让我们知道它是否对您有用,您可以复制并粘贴以下代码
    <?php
    $reviews = apply_filters( 'glsr_get_reviews',[],[
        'order' => 'DESC','orderby' => 'meta_value_key','post_status' => 'publish','post_type' => 'page',// change this as needed
        'posts_per_page' => 5,// change this as needed
    ]);
    $reviews=array_reverse($reviews);//reverse the array itself.
    $limit=0;//initializing counter to track the number of review displayed.
    foreach( $reviews as $review ) {
        $reviewHtml = $review->build(); ?>  
        <p><?php echo $reviewHtml->assigned_to; ?></p>
        <p><?php echo $reviewHtml->rating; ?></p>
        <?php 
            echo '<br/>';
            wp_reset_postdata();
            $limit++;//increasing the limit position to the review that is already processd.
            if($limit==5){//check if limit is reached you can change this limit to whatever you need.
            break;//break the loop after 5 review has been displayed.
            }
        } 
    ?>