【问题标题】:Random results from an array after loop循环后数组的随机结果
【发布时间】:2013-02-05 01:17:19
【问题描述】:

首先,我花了上周的时间将这段代码从很多不同的来源整合在一起,如果你从我遇到的示例中可以看出的话,这是一个真正的科学怪人。我不擅长编写 PHP,但到目前为止已经完成了。任何投入将不胜感激。

我正在做一个项目,我需要从 cat 4 的所有子类别中获取最新的 10 个结果,之后我希望随机化结果并显示。我见过很多使用 shuffle(); 函数的例子,但是在正确实现它时遇到了问题。

这是我的代码:

<?php

$categories = get_categories( 'child_of=4' );
  foreach($categories as $category) {
  $args=array(
  'showposts' => 10,
  'category__in' => array($category->term_id),
  'caller_get_posts'=>1
);
$posts=get_posts($args);
  shuffle($posts);
  if ($posts) {
    foreach($posts as $post) {
      setup_postdata($post); ?>
        <div <?php post_class('boxy');?>>
      <a href="<?php the_permalink() ?>"><?php  the_post_thumbnail(); ?></a>

    <?php the_content(''); ?>
    </div>
      <?php
    } 
  } 
} 
?>

链接到我的结果:Live work in progress

此代码将每个类别中的结果随机化,但按类别显示它们.. 我希望我对看似简单的修复已经足够清楚了。

谢谢

【问题讨论】:

    标签: arrays wordpress loops random shuffle


    【解决方案1】:
    $categories = get_categories( 'child_of=4' );
    $cats = array();
    foreach($categories as $category) {
       $cats[] = $category->term_id;
    }
    
    $args=array(
      'showposts' => 10,
      'category__in' => $cats,
      'orderby' => 'rand',
      'caller_get_posts'=>1
    );
    $posts=get_posts($args);
    

    我希望这将是一个更有效的解决方案。我还没有测试出来。

    【讨论】:

      【解决方案2】:

      您需要首先使用您拥有的所有类别制作所有帖子的数组。比你需要洗牌一样。试试这个,

       $posts = array();
       $categories = get_categories( 'child_of=4' );
       foreach($categories as $category) {
         $args=array(
          'showposts' => 10,
          'category__in' => array($category->term_id),
          'caller_get_posts'=>1
         );
       $posts = $posts + get_posts($args);
      } // Close your foreach here
      

      ....比您的代码原样...

      【讨论】:

      • 工作就像一个魅力,只需将“showposts”的数量更改为更高的数字,因为总共只显示 10 个结果
      • 嗯,我添加了一只新的子猫,它应该与此代码一起显示,但无法显示它。我剪掉了孩子的孩子并能够通过 cat id 专门针对帖子类型显示它们,但是在尝试之后我仍然无法弄清楚为什么新猫不会与其他猫一起显示..
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-24
      • 1970-01-01
      • 2018-03-18
      • 2017-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多