开发者

Title only if foreach exists

I have the following code:

foreach ($model->details as $detail) {
  if ($detail->Title) echo $detail->Title;
  if ($detail->Info) echo '<br />'.$detail->Info;
}

Now I want to add something 开发者_如何学Golike this:

'<h2>Details</h2>'.'<hr />'

to the top of the output but only when the if's in the foreach clause are met. If neither of the if's is met I want nothing to display at all.

Can some help me tweak my code to accomplish this?


Like so?

foreach ($model->details as $detail) {
    if ($detail->Title && $detail->Info) {
         echo '<h2>Details</h2><hr />';
    }
    if ($detail->Title) echo $detail->Title;
    if ($detail->Info) echo '<br />'.$detail->Info;
}

Addendum: I'd probably rather do something like this, to also avoid the uneccessary <br /> when there's no Title, but only Info

foreach ($model->details as $detail) {
    $text = array();
    if ($detail->Title) $text[] = $detail->Title;
    if ($detail->Info)  $text[] = $detail->Info;
    if (!empty($text)) {
        echo '<h2>Details</h2><hr />';
        echo implode('<br />', $text);
    }
}


You need to output to a string, or use the output buffering. The following example uses the string approach:

$sOutputHtml = NULL;

foreach ($model->details as $detail) {
  if ($detail->Title) $sOutputHtml .= $detail->Title;
  if ($detail->Info) $sOutputHtml .= '<br />'.$detail->Info;
}

if ($sOutputHtml !== NULL) {
  echo '<h2>Details</h2>'.'<hr />' . $sOutputHtml;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜