2016-04-22 59 views
-3

我的$数组有32个值,我想使用循环,但我不知道。如何在php中使用循环

if ($array[0] > 1) 
{ 
    echo $array[0]; 
    unset($array[0]); 
} 

else if ($array[1] > 1) 
{ 
    echo $array[1]; 
    unset($array[1]); 
} 

else if ($array[2] > 1) 
{ 
    echo $array[2]; 
    unset($array[2]); 
} 
else 
{ 
    echo "<a href=' ".$_SERVER['PHP_SELF']."?month=".$monthstring."&day=".$daystring."&year=".$year." '>".$i." </a></td>"; 
} 
+1

你究竟想要做什么? – T0xicCode

+1

您可以使用[foreach](http://php.net/manual/en/control-structures.foreach.php),[for](http://php.net/manual/en/control-structures.for .php)或[while](http://php.net/manual/en/control-structures.while.php)遍历数组。 – JimL

+0

我可以看到有一个$ i变量,从它看起来你已经尝试循环? – chba

回答

0

我想是这样的

foreach($array as $index => $value) 
{ 
    if ($value > 1) 
    { 
     echo $value; 
     unset($array[$index]); 
    } 
    else 
    { 
     echo '<a href="', $_SERVER['PHP_SELF'], '?month=', $monthstring, '&day=', $daystring, '&year=', $year, '>', $index, '</a>'; 
    } 
} 
+0

Almost.Works好,但如果其他人不好 –

+0

那还有什么问题?你想在哪一点停止循环?可能是我错过了一个观点。您可能会使用Barmar的解决方案,但是您可以避免$删除的变量,并在其他括号中的回声后立即制动。 – chba

0

否则是整个循环后,我想应该是这样的:

$found = false; 
foreach($array as $index => $value) 
{ 
    if ($value > 1) 
    { 
     echo $value; 
     unset($array[$index]); 
     $found = true; 
     break; 
    } 
} 
if(!$found) { 
    echo '<a href="', $_SERVER['PHP_SELF'], '?month=', $monthstring, '&day=', $daystring, '&year=', $year, '>', $index, '</a>'; 
} 
+0

原始代码只回应和取消找到的第一个值,而不是全部。这就是为什么我的答案突破了循环。 – Barmar

+0

忘了打破,修复,谢谢@Barmar –

0

使用foreach循环,跳出来在取消设置大于1的第一个元素后,使用变量来跟踪是否删除了任何内容,因此您知道是否在循环后回显锚点。

$deleted = false; 
foreach ($array as $index => $value) { 
    if ($value > 1) { 
     echo $value; 
     unset($array[$value]); 
     $deleted = true; 
     break; 
    } 
} 
if (!$deleted) { 
    echo "<a href=' ".$_SERVER['PHP_SELF']."?month=".$monthstring."&day=".$daystring."&year=".$year." '>".$i." </a></td>"; 
}