简体   繁体   English

如何在PHP的while循环内进行if if条件?

[英]How to make an if else condition within a while loop in php?

I want to make an array that looks like this: 我想制作一个看起来像这样的数组:

qqq = [[a,b],[c,d]];

But with the code that I got it makes an output that looks like this: 但是用我得到的代码,它的输出看起来像这样:

qqq= [[a,b],[c,d],];

what should i do to exclude the extra semicolon? 我应该怎么做才能排除多余的分号?

var qqq = [<?php 
        $aw = "select * from city;";
        $wa = mysql_query($aw);

    while($aa = mysql_fetch_array($wa))
        {       
            $cc = $aa['Coordinate_id'];
            $bb = $aa['city_name'];

            echo "[$cc,$bb],";

        }   
?> ];

Since you are going for a JSON encoded array, please use the following snippet to achieve exactly the same: 由于您要使用JSON编码的数组,因此请使用以下代码片段实现完全相同的效果:

var qqq = <?php 
    $aw = "select * from city;";
    $wa = mysql_query($get_marker);

    $arr = array();
    while($aa = mysql_fetch_array($wa)) {
        $arr[] = array($aa['Coordinate_id'], $aa['city_name']);
    }
    echo json_encode($arr);
?>;

Replace this: 替换为:

while($aa = mysql_fetch_array($wa))
{
    $cc = $aa['Coordinate_id'];
    $bb = $aa['city_name'];
    echo "[$cc,$bb],";
}

to this: 对此:

$result = '';
while($aa = mysql_fetch_array($wa))
{
    $cc = $aa['Coordinate_id'];
    $bb = $aa['city_name'];
    result.="[$cc,$bb],";
} 
echo trim($result,',');

Instead of echo you should use implode like this 而不是回声,您应该使用像这样的内爆

<?php 
$aw = "select * from city;";
$wa = mysql_query($get_marker);
$arr = [];
while($aa = mysql_fetch_array($wa))
{       
    $cc = $aa['Coordinate_id'];
    $bb = $aa['city_name'];

    $arr[] = "[$cc,$bb]";
}   
?>

var qqq = [<?php echo implode(',',$arr)?>];

I think this improves readability as well and is more easily ported to something more manageable 我认为这也提高了可读性,并且更容易移植到更易于管理的地方

Count the number of rows: 计算行数:

$num = mysql_num_rows($aw);

And check if the condition applies that the last loop is occurring by using a counter: 并使用计数器检查条件是否适用于发生最后一个循环:

$i = 0;
while($aa = mysql_fetch_array($wa))
{       
    $cc = $aa['Coordinate_id'];
    $bb = $aa['city_name'];

    if ($i < $num)
    {
        echo "[$cc,$bb],";
    }
    else
    {
        echo "[$cc,$bb]";
    }
    $i++;
}   

Finally, note that mysql_* functions are deprecated and should be avoided. 最后,请注意mysql_ *函数已被弃用,应避免使用。 Use PDO or mysqli instead. 改用PDO或mysqli。

Use an array instead of echo and implode outside while loop 使用数组代替echo并在while循环内爆

var qqq = [<?php 
    $aw = "select * from city;";
    $wa = mysql_query($get_marker);

$ret = array();

while($aa = mysql_fetch_array($wa))
{       
    $cc = $aa['Coordinate_id'];
    $bb = $aa['city_name'];

    $ret[] = "[$cc,$bb]";

}   

echo implode(',', $ret);
?> ];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM