同时删除一个字符

时间:2016-11-20 13:13:27

标签: php

如何在while内修剪一个字符?见这个例子:

  

我想要的是什么:

[{"lat":"mylat","lng":"mylong","dragable":"false"},
 {"lat":"mylat","lng":"mylong","dragable":"false"}]`
     

我得到了什么:

[{"lat":"mylat","lng":"mylong","dragable":"false"},
 {"lat":"mylat","lng":"","dragable":"false"},]

我想删除}]之间的逗号,但我不知道如何。

代码:

print "[";
if ($result=mysqli_query($conn,$sql)) {
  while ($row=mysqli_fetch_row($result)) {
    $locs_json = sprintf(json_encode(array("lat"=>"%s", "lng"=>"%s", "dragable"=>"false")),$row[0],$row[1]);
    $locs = $locs_json.",";
    print $locs;
  }
  mysqli_free_result($result);
}
print "]";

我尝试在打印后添加rtrim($locs, ",");,但它删除了所有逗号,除了最后一个,我需要所有逗号。

3 个答案:

答案 0 :(得分:1)

我会将字符串存储在变量中。

完成添加值后,执行ggplot() + geom_polygon(data = plotDatafr, aes(x = long, y = lat, group = group, fill = item, alpha = score), colour = NA) + scale_fill_manual(values = c("#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7"), name = "", na.value=NA) + coord_map(),然后添加方括号并打印。

rtrim

答案 1 :(得分:1)

您似乎尝试使用json_encode()编码为JSON,部分手动编码。您可以json_encode()完成所有工作:

$rows = [];
if ($result = mysqli_query($conn, $sql)) {
    while ($row = mysqli_fetch_row($result)) {
        $rows[] = [
            'lat' => $row[0],
            'lng' => $row[1],
            'dragable' => 'false',
        ];
    }
    mysqli_free_result($result);
}

echo json_encode($rows);

答案 2 :(得分:0)

print "[";
if ($result=mysqli_query($conn,$sql)) {
  $i = 1;
  while ($row=mysqli_fetch_row($result)) {
    $locs_json = sprintf(json_encode(array("lat"=>"%s", "lng"=>"%s", "dragable"=>"false")),$row[0],$row[1]);

    echo ($i >1 && !empty($locs_json)) ? ',' : '';
    print $locs_json;
    $i++;
  }
  mysqli_free_result($result);
}
print "]";

简单解决方案:根据计数器值

添加计数器并打印逗号