1

对 PHP 来说很新,我试图让我的页面显示 3 个博客条目,然后是 3 张照片,然后是另外 3 个博客条目,依此类推。

有人建议我使用 do while 循环,但很难让它工作,甚至很难理解它,我更习惯于在 CMS 中使用 foreach 循环。

这是我的原始代码,但前提是我手动显式添加了每个循环!

   <?php  // Show 3 blog entries
$entries = $page->children("sort=-sort, limit=3");
$count = 0;

foreach ($entries as $entry) { 

$count++; 
$class = "blog_box"; 
if ($entry == $entries->last()) {$class .= " blog_box_last"; }
if ($entry == $entries->first()) {$class .= " blog_box_first"; }
if (0 == $count % 2) { $class .= " blog_box_even"; }
?>

<div class="<?php echo $class; ?>">

<div class="blog_text">

<h3><?php echo $entry->title; ?></h3>
<h6><?php echo $entry->entry_date; ?></h6>
<p><?php echo $entry->body; ?></p>

</div><!-- /.blog_text -->

<?php if ($entry->image) { 

$image = $entry->image->width(350);

?>

<img src="<?php echo $image->url; ?>" width="<?php echo $image->width; ?>" alt="<?php echo $entry->title; ?>" />

<?php } ?>

<div class="clear"></div><!-- /.clear -->

</div><!-- /.blog_box -->

<?php }

?>

// Show 3 blog images

<?php $blog_images = $page->get("image_uploads")->find("limit=3");
foreach ($blog_images as $img) { 
$b_img = $img->size(200,140); ?>
<img src="<?php echo $b_img->url; ?>" width="<?php echo $b_img->width; ?>" height="<?php echo $b_img->height; ?>" alt="<?php echo $b_img->description; ?>" class="small_frame" />
<?php } ?>

CMS 开发人员好心地为我尝试了一些代码,但我无法让它为我工作:

    $entries = $page->children("sort=-sort");
$images = $page->get("/image_uploads/"); 
$cnt = 0;

do {
    $cnt++; 
    $entry = $entries->shift();
    if($entry) {
        // output 1 entry
    }

    if($cnt == 3) {
        while(++$cnt <= 6) {
            $image = $images->shift();
            if($image) {
                // output 1 image
            }
        }
        $cnt = 0;
    }

} while(count($entries) && count($images));

我正在使用 ProcessWire。

提前谢谢各位!

4

0 回答 0