【问题标题】:how to stop echo statement from echoing multiple times while inside nested loops如何在嵌套循环中停止回显语句多次回显
【发布时间】:2015-05-27 02:59:43
【问题描述】:

我有以下查询结构

结构

//note the value in $array isan array sent from the client side script
$q1 = mysqli_query($db,'query stuff')or trigger_error(mysqli_error());
if(mysqli_num_rows($q1) >=1 )
{
    while($row = mysqli_fetch_assoc($query)) // while loop 1
    {
        $q2 = mysqli_query($db,'query stuff') or trigger_error(mysqli_error());
        if(mysqli_num_rows($q2)>=1)
        {
            while($r=mysqli_fetch_assoc($2)) // while loop 2
            {
                for($i=0;$i<sizeof($array);$i++) // forloop
                {
                    if( \\validate conditions )
                    {
                        echo $i;//echoes 0101 instead of 01
                    }
                }
            }
        }
    }
}

解释: 上面的代码包含2个while循环和1个for循环。for循环嵌套在一个while中,而while又嵌套在另一个while循环中。当我输出代码时,预期的输出是01,但它返回0101

如何阻止这种情况发生


我尝试了什么

我尝试了以下结构

            .....
            $tab_exists = false;
            while($r=mysqli_fetch_assoc(q2))//while loop 2
            {
                for($i=0;$i<sizeof($array);$i++) // for loop
                {
                       if(!$tab_exists)
                       {
                           echo $i;//echoes 00 instead of 01
                           $tab_exists = true;
                       }
                }
            }

上述结构的结果:在上述代码中,语句中的 $i 不递增

【问题讨论】:

  • 当人为设计的示例排除了任何原始意图的线索时,很难找出问题所在。显然,您对内部循环的迭代次数比预期的要多,购买为什么仍然未知。也许简单地通过计数器限制输出会起作用,但我怀疑这是一个好的解决方案。请提供更多详细信息
  • 存在内部循环(即 for 循环)是因为我将一组值发送到服务器进行验证

标签: php for-loop while-loop nested nested-loops


【解决方案1】:

试试这个:

$q1 = mysqli_query($db,'query stuff')or trigger_error(mysqli_error());
$count =0;
if(mysqli_num_rows($q1) >=1 )
{
    while($row = mysqli_fetch_assoc($query))
    {
        $q2 = mysqli_query($db,'query stuff') or trigger_error(mysqli_error());
        if(mysqli_num_rows($q2)>=1)
        {
            while($r=mysqli_fetch_assoc($2))
            {
                for($i=0;$i<sizeof($array);$i++)
                {
                    if( \\validate conditions && $count<=2)
                    {
                        echo $i;//echoes 0101 instead of 01
                        $count++;
                    }
                }
            }
        }
    }
}

【讨论】:

  • 为什么条件应该是count&lt;=2
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-26
相关资源
最近更新 更多