我有一个小问题,我无法用嵌套的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
并在每次迭代时只打印一个值?
答案 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)];