Reputation: 21
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],";
}
?> ];
Upvotes: 2
Views: 112
Reputation: 898
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,',');
Upvotes: 2
Reputation: 3097
Since you are going for a JSON encoded array, please use the following snippet to achieve exactly the same:
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);
?>;
Upvotes: 3
Reputation: 259
Use an array instead of echo and implode outside while loop
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);
?> ];
Upvotes: 0
Reputation: 4967
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. Use PDO or mysqli instead.
Upvotes: 0
Reputation: 163
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
Upvotes: 0