【问题标题】:Foreach inside if() | if() close issueif() 内部的 foreach | if() 关闭问题
【发布时间】:2014-06-05 07:10:20
【问题描述】:
我将 foreach 语句放在 if 语句中,但在关闭 if 语句时遇到问题。 if 检查“类型”,如果条目类型与选择的“类型”匹配,它将使用 foreach 输出具有该“类型”的所有条目。
这是一个例子。
<?php
if($row->type == 'HTML')
{
foreach($content as $row): ?>
<h2><?= $row->title ?></h2>
<span class="rating"> <?= $row->rating?>/5</span>
<p class="desc"><?= $row->description ?> </p>
<span class="date"><?= $row->created ?> </span>
<a href="<?= $row->url ?>">View Tutorial</a>
<span class="diff"><?= $row->difficulty ?></span>
<span class="auth">Added by </span>
<?php } else {
echo 'No results found';
}
endforeach; ?>
【问题讨论】:
标签:
php
codeigniter
if-statement
foreach
【解决方案1】:
你会在循环中找到$row,所以将if() else保留在foreach中以获取$row->type
<?php
foreach($content as $row):
if($row->type == 'HTML')
{?>
<h2><?= $row->title ?></h2>
<span class="rating"> <?= $row->rating?>/5</span>
<p class="desc"><?= $row->description ?> </p>
<span class="date"><?= $row->created ?> </span>
<a href="<?= $row->url ?>">View Tutorial</a>
<span class="diff"><?= $row->difficulty ?></span>
<span class="auth">Added by </span>
<?php } else {
echo 'No results found';
}
endforeach; ?>
【解决方案2】:
<?php
foreach($content as $row):
if($row->type == 'HTML') { ?>
<h2><?= $row->title ?></h2> <span class="rating"> <?= $row->rating?>/5</span>
<p class="desc"><?= $row->description ?> </p>
<span class="date"><?= $row->created ?> </span>
<a href="<?= $row->url ?>">View Tutorial</a>
<span class="diff"><?= $row->difficulty ?></span>
<span class="auth">Added by </span>
<?php
} else {
echo 'No results found';
}
endforeach; ?>
【解决方案3】:
你的结构应该是:
你的结构是
您可能正在寻找这个:
<?php
$found = FALSE; // used to track whether something has been found.
foreach($content as $row){
if($row->type == 'HTML')
{
$found = TRUE; // there is at least one row with ->type == 'HTML'
?>
<h2><?= $row->title ?></h2>
<span class="rating"> <?= $row->rating?>/5</span>
<p class="desc"><?= $row->description ?> </p>
<span class="date"><?= $row->created ?> </span>
<a href="<?= $row->url ?>">View Tutorial</a>
<span class="diff"><?= $row->difficulty ?></span>
<span class="auth">Added by </span>
<?php
}
}; // moved to the {} closing
// test whether any valid rows have been found (set above)
if(!$found){echo 'No results found';}
?>
【解决方案4】:
你的条件必须是这样的:
<?php
foreach($content as $row): ?>
if($row->type == 'HTML')
{
<h2><?= $row->title ?></h2>
<span class="rating"> <?= $row->rating?>/5</span>
<p class="desc"><?= $row->description ?> </p>
<span class="date"><?= $row->created ?> </span>
<a href="<?= $row->url ?>">View Tutorial</a>
<span class="diff"><?= $row->difficulty ?></span>
<span class="auth">Added by </span>
<?php } else {
echo 'No results found';
}
?>
<?php endforeach; ?>
您的 foreach 条件应高于 if else 条件。