doushu2699 2014-05-15 14:52
浏览 35
已采纳

如何一次在两个位置使用foreach数据?

I have a foreach loop which contains a series of data, but what I need is for that data to display in two seperate locations.

Basically this is because i have:

<div id="maindivofimage">
 <?php foreach($bannerdata as $banner): ?>
    <img src="<?php echo $banner->getImage();?> />
 <?php endforeach; ?>
</div>

<div id="maindivofcontent">
    <h1><?php $banner->getTitle();?> </h1>
    <p><?php $banner->getDescription();?> </p>
</div>

and I only want a single surrounding DIV for each section, so I can't put the section section within the foreach or it'll display it multiple times...

Any help greatly appreciated!

  • 写回答

1条回答 默认 最新

  • dongyao2001 2014-05-15 14:59
    关注

    I am sure there is no problem at all with running the same loop twice, but if you really want to, you can run it once and store the html into strings, then use the strings:

    <?php 
    $imgs='';
    $text='';
    foreach($bannerdata as $banner){
    
        $imgs .= '<img src="'.$banner->getImage().'" />';
        $text .= '<h1>'.$banner->getTitle().'</h1>';
        $text .= '<p>'.$banner->getDescription().'</p>';
    }; ?>
    
    <div id="maindivofimage">
         <?php echo $imgs;?>
    </div>
    
    <div id="maindivofcontent">
        <?php echo $text;?>
    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀