该代码循环一个数组,并为用户显示所有视图。现在情况发生了变化,我只需要显示foreach循环的一个结果。我该怎么做?
<table class="report_edits_table">
<thead>
<tr class="dates_row">
<?php foreach($report['edits'] as $report_edit) : ?>
<td colspan="2" report_edit_id="<?php echo $report_edit['id'] ?>"><div class="date_container">
<?php if($sf_user->hasCredential(Attribute::COACHING_EDIT_ACCESS)) : ?>
<span class="ui-icon ui-icon-trash">Remove</span>
<?php endif?>
<?php echo "View " . link_to($report_edit['created'], sprintf('coaching/viewReportEdit?reportedit=%s', $report_edit['id']), array('title' => 'View This Contact')) ?> </div></td>
<?php endforeach ?>
</tr>
</thead>
<tbody>
<?php foreach($report['edits_titles'] as $index => $title) : ?>
<tr class="coach_row">
<?php for ($i=max(0, count($report['edits'])-2); $i<count($report['edits']); $i++) : $report_edit = $report['edits'][$i] ?>
<td class="name_column"><?php echo $title ?></td>
<td class="value_column"><?php echo $report_edit[$index] ?></td>
<?php endfor ?>
</tr>
<?php endforeach ?>
</tbody>
发布于 2011-10-07 23:47:58
使用break命令进行简单转换:
<?php for ... ?>
... stuff here ...
<?php break; ?>
<?php endfor ... ?>更好的解决方案是完全删除foreach。
发布于 2011-10-07 23:55:58
听起来您想要从数组中抓取第一个元素,而不必遍历其他元素。
PHP为这种情况提供了一组函数。
要获取数组中的第一个元素,首先使用reset()函数将数组指针定位到数组的开头,然后使用current()函数读取指针正在查看的元素。
因此,您的代码将如下所示:
<?php
reset($report['edits']);
$report_edit = current($report['edits']);
?>现在,您可以使用$report_edits,而不必使用foreach()循环。
(请注意,默认情况下,数组指针实际上从第一个记录开始,因此您可以跳过reset()调用,但最佳实践是不要这样做,因为它可能在您未意识到的情况下在代码中的其他地方被更改了)
如果您想转到下一条记录,可以使用next()函数。正如您所看到的,如果您愿意,理论上可以使用这些函数编写另一种类型的foreach()循环。以这种方式使用它们没有任何意义,但这是可能的。但它们确实允许对数组进行更细粒度的控制,这对于您这样的情况很方便。
希望这能有所帮助。
发布于 2011-10-07 23:47:49
有很多方法
无论逻辑提取/生成的是什么,都要访问相关数组元素的索引,以便只返回感兴趣的元素。使用在单个loop
循环来获取感兴趣的元素,并在foreach循环结束时中断
<
我建议只获取感兴趣的数组元素(列表中的第2个),因为这意味着在代码中跳跃的数据更少(如果是从SQL服务器填充数组,则可能在PHP机器和数据库之间)
https://stackoverflow.com/questions/7689626
复制相似问题