问题很简单。我有一个foreach循环在我的代码:
foreach($array as $element) {
//code
}
在这个循环中,当我们在第一次或最后一次迭代时,我希望做出不同的反应。
如何做到这一点?
问题很简单。我有一个foreach循环在我的代码:
foreach($array as $element) {
//code
}
在这个循环中,当我们在第一次或最后一次迭代时,我希望做出不同的反应。
如何做到这一点?
当前回答
对于SQL查询生成脚本,或任何对第一个或最后一个元素执行不同操作的脚本,避免使用不必要的变量检查要快得多(几乎快两倍)。
目前公认的解决方案使用循环和循环内的检查,将使every_single_iteration,正确的(快速)方法如下:
$numItems = count($arr);
$i=0;
$firstitem=$arr[0];
$i++;
while($i<$numItems-1){
$some_item=$arr[$i];
$i++;
}
$last_item=$arr[$i];
$i++;
一个自制的基准测试显示如下:
Test1: 100000次模型morg
时间:1869.3430423737毫秒
Test2:模型运行100000次
时间:3235.6359958649毫秒
因此,很明显,支票的成本很高,当然,你添加的变量越多,情况就越糟糕;)
其他回答
你可以用一个计数器:
$i = 0;
$len = count($array);
foreach ($array as $item) {
if ($i == 0) {
// first
} else if ($i == $len - 1) {
// last
}
// …
$i++;
}
最简单的方法是
$array = [9,5,6,4,7,8];
$current_iteration = 0;
foreach($array as $item){
if( 0 === $current_iteration ){
echo 'this is the first item: ' . $item;
}
if( (count($array) - 1) === $current_iteration){
echo 'this is the last item: ' . $item;
}
$current_iteration++;
}
试试这个:
function children( &$parents, $parent, $selected ){
if ($parents[$parent]){
$list = '<ul>';
$counter = count($parents[$parent]);
$class = array('first');
foreach ($parents[$parent] as $child){
if ($child['id'] == $selected) $class[] = 'active';
if (!--$counter) $class[] = 'last';
$list .= '<li class="' . implode(' ', $class) . '"><div><a href="]?id=' . $child['id'] . '" alt="' . $child['name'] . '">' . $child['name'] . '</a></div></li>';
$class = array();
$list .= children($parents, $child['id'], $selected);
}
$list .= '</ul>';
return $list;
}
}
$output .= children( $parents, 0, $p_industry_id);
为了找到最后一项,我发现这段代码每次都有效:
foreach( $items as $item ) {
if( !next( $items ) ) {
echo 'Last Item';
}
}
当我遇到同样的问题时,我遇到了这条线索。我只需要得到第一个元素,然后我重新分析我的代码,直到这出现在我的脑海中。
$firstElement = true;
foreach ($reportData->result() as $row)
{
if($firstElement) { echo "first element"; $firstElement=false; }
// Other lines of codes here
}
上面的代码是伟大的和完整的,但如果你只需要第一个元素,那么你可以试试这段代码。