2011-10-07 84 views
4

该代码循环一个数组并显示用户的所有视图。现在事情改变了,我只需要显示一个foreach循环的结果。我怎么做?如何从foreach中获取一个结果(PHP)

<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> 

+0

我真的不知道你想做什么,但你总是可以'打破;'跳出'的foreach( )' – jprofitt

回答

2

简单转换使用break命令:

<?php for ... ?> 
    ... stuff here ... 
    <?php break; ?> 
<?php endfor ... ?> 

一个更好的解决办法是彻底清除foreach

1

最简单的方法?

break作为您的foreach的最后一行。它会执行一次,然后退出。 (只要其中元素你停下来是没有意义的)。

次要方法:你$report['edits']$report['edits_titles']获得元素上,失去了for循环,并引用元素上使用array_poparray_shift你只是检索。

例如:

// 
// current 
// 
foreach ($report['edits'] as $report_edit) : 
    /* markup */ 
endforeach; 

// 
// modified version 
// 
$report_edit = array_shift($report['edits']); 
    /* markup */ 
3

方式大量

  1. 访问所讨论的阵列元件直接
  2. 更新任何逻辑取/的索引生成所述阵列,以仅返回的元件兴趣
  3. 使用for循环在单个循环后终止
  4. arr ay_filter您的阵列来获取感兴趣的元素
  5. 歇在您的foreach循环的末尾,以便它在第一次迭代之后终止
  6. 有条件的检查在foreach循环中,只有输出标记指数,如果指数感兴趣的元素相匹配
  7. 等等

我建议刚开始的利息(名单上的数字2),因为它意味着更少的数据在你的代码弹跳数组元素(也可能是你的PHP箱和数据库之间是否你正在从SQL服务器填充数组)

1

使用<?php break ?><?php endforeach ?>

4

这听起来像你想抓住从一个数组的第一个元素,而无需通过他们的休息有循环。

PHP为这种情况提供了一组函数。

要获得数组中的第一个元素,请使用reset()函数将数组指针定位到数组的起始位置,然后使用current()函数读取指针正在查看的元素。

所以,你的代码应该是这样的:

<?php 
reset($report['edits']); 
$report_edit = current($report['edits']); 
?> 

现在你可以用$report_edits工作,而无需使用foreach()循环。

(注意,数组指针不实际默认的第一个记录开始,所以你可以跳过reset()电话,但最好的做法不是这样做,因为它可能已在其他地方在你的代码改变,而你意识到这一点)

如果你想在此之后移动到下一个记录,你可以使用next()函数。正如你所看到的,如果你愿意,理论上可以使用这些函数来编写另一种类型的foreach()循环。以这种方式使用它们没有任何意义,但它是可能的。但是它们确实允许对数组进行更细粒度的控制,这对于像您这样的情况非常方便。

希望有所帮助。

1
example :: 

<?php 
    foreach ($this->oFuelData AS $aFuelData) { 
    echo $aFuelData['vehicle']; 
    break;      
    } 
?> 
0

你也可以用它来参考

foreach($array as $element) { 
    if ($element === reset($array)) 
     echo $element; 

    if ($element === end($array)) 
     echo $element; 
    }