嵌套的foreach循环(3项+ 1 /循环)

时间:2014-05-19 08:26:14

标签: php foreach

我有一个小问题,我无法用嵌套的foreach循环弄清楚(PHP初学者)。我想要实现的是这样的结构:

<div class="slide-testimonials">
   <span class="item"><img src="" /></span>
   <span class="item"><img src="" /></span>
   <span class="item"><img src="" /></span>
</div>
Sales People
<div class="slide-testimonials">
    <span class="item"><img src="" /></span>
    <span class="item"><img src="" /></span>
    <span class="item"><img src="" /></span>
</div>
Freelancers
<div class="slide-testimonials">
    <span class="item"><img src="" /></span>
    <span class="item"><img src="" /></span>
    <span class="item"><img src="" /></span>
</div>
Sales Managers

我现在得到的是:

<div class="slide-testimonials">
   <span class="item"><img src="" /></span>
   <span class="item"><img src="" /></span>
   <span class="item"><img src="" /></span>
</div>
Sales PeopleFreelancersSales Managers
<div class="slide-testimonials">
    <span class="item"><img src="" /></span>
    <span class="item"><img src="" /></span>
    <span class="item"><img src="" /></span>
</div>
Sales PeopleFreelancersSales Managers
<div class="slide-testimonials">
    <span class="item"><img src="" /></span>
    <span class="item"><img src="" /></span>
    <span class="item"><img src="" /></span>
</div>
Sales PeopleFreelancersSales Managers

我使用的foreach循环是:

<?php 
    $post_type = 'testimonial';
    global $wpdb;
    $where = get_posts_by_author_sql( $post_type );
    $query = "SELECT * FROM $wpdb->posts p where p.post_type = 'attachment' AND (p.post_mime_type LIKE 'image/%')  AND (p.post_status = 'inherit') AND p.post_parent IN (SELECT $wpdb->posts.ID FROM $wpdb->posts  {$where} ) ORDER BY p.post_date DESC";
    $results =  $wpdb->get_results( $query );   
    $arrayName = array('title1' => 'Sales People', 'title2' => 'Freelancers', 'title3' => 'Sales Managers' );               
    $count = 0;
        foreach ($results as $image) {
            $thumb = wp_get_attachment_thumb_url( $image->ID );
            $alt = get_post_meta($image->ID, '_wp_attachment_image_alt', true);
                if ($count % 3 == 0) {
                    echo "<div class='slide-testimonials'>";
                }
        $count++;
?>
<span class='item'> <?php print '<img class="image" src="' . $thumb . '" alt="' . $alt . '" />' ?> </span>
<?php
    if ($count % 3 == 0) {
        echo "</div>";
            foreach($arrayName as $value) {
            print $value;
            }
    }
}
?>

如何遍历array并在每次迭代时只打印一个值?

2 个答案:

答案 0 :(得分:2)

在第二个$nameCount条件中再添加一个计数器if$nameCount = 1;foreach循环之前声明此内容,并在第二if条件下使用下面的代码。

if ($count % 3 == 0) {
   echo "</div>";echo $arrayName['title'.$nameCount];
   $nameCount++;
}

答案 1 :(得分:0)

使用第一个循环执行此操作:

foreach($results as $id=>$image) {

然后用:

替换你的第二个循环
echo $arrayName['title'.($id+1)];