How do I echo out something different when reached last row?
I am wanting to not echo out the comma at the end of the echo after the last row. How can I do that? Here is my code:
<?php
header("Content-type开发者_StackOverflow中文版: application/json");
echo '{"points":[';
mysql_connect("localhost", "user", "password");
mysql_select_db("database");
$q = "SELECT venues.id, venues.lat, venues.lon, heat_indexes.temperature FROM venues, heat_indexes WHERE venues.id = heat_indexes.venue_id";
$res = mysql_query($q) or die(mysql_error());
while ($point = mysql_fetch_assoc($res)) {
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'] . ",";
}
mysql_free_result($res);
echo ']}';
?>
Could you not use json_encode()
instead, rather than hand-crafting the JSON?
$result = array();
//snip
while ($point = mysql_fetch_assoc($res)) {
$result[] = $point['lat'];
$result[] = $point['lon'];
$result[] = $point['temperature'];
}
//snip
header("Content-type: application/json");
echo json_encode( array('points' => $result) );
Use a count query to get the number of rows to begin with.
$query= "SELECT COUNT(*) FROM venues";
$count= mysql_query($q);
Then introduce a conditional and a count decrease each time through...
while ($point = mysql_fetch_assoc($res)) {
$count = $count - 1;
if ($count == 1) {
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'];
} else {
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'] . ",";
}
Json encode would probably be your best bet, but you could also use trim();
Rather than echoing in the while loop, append to a variable. Once outside the while loop, use $output = trim($output, ',') to remove trailing commas.
About the comma problem, I always target the first item instead of the last:
$first = true;
while ($point = mysql_fetch_assoc($res)) {
if ($first)
{
$first = false;
}
else
{
echo ",";
}
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'];
}
You can use mysql_num_rows()
to find out how many rows are in the result set passed back from your last query.
...
$res = mysql_query($q) or die(mysql_error());
$num_rows = mysql_num_rows($res);
Then combine that with Scotts answer and you should be set.
精彩评论