到达最后一行时,如何回应不同的东西?

时间:2010-04-16 14:38:04

标签: php mysql

我想在最后一行之后的回声结束时不回显逗号。我怎样才能做到这一点?这是我的代码:

<?php
    header("Content-type: 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 ']}';
    ?>

5 个答案:

答案 0 :(得分:1)

您是否可以不使用json_encode()而不是手工制作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) );

答案 1 :(得分:0)

使用计数查询来获取要开始的行数。

$query= "SELECT COUNT(*) FROM venues";
$count= mysql_query($q);

然后每次通过......引入条件和计数减少

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'] . ",";
    }

答案 2 :(得分:0)

Json编码可能是你最好的选择,但你也可以使用trim();

不是在while循环中回显,而是附加到变量。一旦在while循环之外,使用$ output = trim($ output,',')删除尾随逗号。

答案 3 :(得分:0)

关于逗号问题,我总是以第一项而不是最后一项为目标:

$first = true;
while ($point = mysql_fetch_assoc($res)) {
    if ($first)
    {
        $first = false;
    }
    else
    {
        echo ",";
    }
    echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'];
}

答案 4 :(得分:0)

您可以使用mysql_num_rows()查看从上次查询传回的结果集中有多少行。

...
$res = mysql_query($q) or die(mysql_error());
$num_rows = mysql_num_rows($res);

然后将其与Scotts答案结合起来,你应该设置好。