Foreach while循环php问题
我试图在每一行的新行上仅显示此数组中不为空的名称。目前,使用它,它仅显示“$playerName1”的名称10次。我想弄明白为什么它没有在所有10个playerName中循环。它似乎只是在检查$playerName1Foreach while循环php问题,php,while-loop,Php,While Loop,我试图在每一行的新行上仅显示此数组中不为空的名称。目前,使用它,它仅显示“$playerName1”的名称10次。我想弄明白为什么它没有在所有10个playerName中循环。它似乎只是在检查$playerName1 $z = array($playerName1, $playerName2, $playerName3, $playerName4, $playerName5, $playerName6, $playerName7, $playerName8, $playerName9, $pla
$z = array($playerName1, $playerName2, $playerName3, $playerName4, $playerName5, $playerName6, $playerName7, $playerName8, $playerName9, $playerName10);
$zCounter = 1;
foreach ($z as $allNames) {
while ($allNames != "" && $zCounter < 11) {
echo $allNames . "<br>";
$zCounter++;
}
}
$z=array($playerName1、$playerName2、$playerName3、$playerName4、$playerName5、$playerName6、$playerName7、$playerName8、$playerName9、$playerName10);
$zCounter=1;
foreach($z作为$allNames){
而($allNames!=''&&$zCounter<11){
echo$allNames。“
”;
$zCounter++;
}
}
您需要在每次while循环后重置$z计数器
foreach ($z as $allNames) {
while ($allNames != "" && $zCounter < 11) {
echo $allNames . "<br>";
$zCounter++;
}
$zCounter = 0;
}
foreach($z作为$allNames){
而($allNames!=''&&$zCounter<11){
echo$allNames。“
”;
$zCounter++;
}
$zCounter=0;
}
否则,在第一个while循环完成后,$zCounter将始终为11您的问题是,您正在执行内部
while
循环,仅针对第一个玩家名称。外部foreach
循环应足够:
foreach ($z as $playerName) {
if ("" !== $playerName) {
echo $playerName . "<br />";
}
}
foreach($z作为$playerName){
如果(“!==$playerName){
echo$playerName.“
”;
}
}
除非您想将每个名称输出10次,否则请在循环时删除。您仍然可以使用!=''检查以确保名称不为空代码>或空()
摆脱内部的while
循环。在一个与问题无关但出现在代码中的问题上。谢谢,真的很感激。为什么否决票可以完美地解决他的问题。他没有说不想让每个人都展示10次。
<?php
$z = array($playerName1, $playerName2, $playerName3, $playerName4, $playerName5, $playerName6, $playerName7, $playerName8, $playerName9, $playerName10);
foreach($z as $name){
if(!empty($name)){
echo $name.'<br>';
}
}