2013-02-20 98 views
0

首先,我花了最后一周的时间,并将这些代码从多个不同的来源组合在一起,如果您将从我遇到的示例中获得一个真正的frankenstein。我不擅长编写PHP,但迄今为止做了很多。任何投入将不胜感激。循环后的数组随机结果

我正在研究一个项目,在该项目中我需要从猫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在每个类别

此代码是随机的结果,而是按类别显示他们.. 我希望我已经明确足以应付看起来像是一个简单的问题。

感谢

回答

1

你需要让所有职位的阵列首先与你有所有类别。比你需要洗牌一样。试试这个,

$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 

....比你的代码,因为它是...

+0

工作就像一个魅力,只需要将'showposts'的数量更改为一个更高的数字,因为是只显示10个结果总计 – StephenPerrett 2013-02-21 22:00:57

+0

嗯,我添加了一个新的儿童猫,应该显示与此代码广告我遇到麻烦它来显示。我剪掉了孩子,并能够通过特定的帖子类型的猫ID显示他们,但尝试后,我仍然无法确定为什么新的猫不会与其他人一起显示.. – StephenPerrett 2013-02-24 20:27:39

0
$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); 

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