Diego Barreiro Diego Barreiro - 15 days ago 6
PHP Question

Remove just one char in while

How can I trim just one character inside a

while
? See this example:


What I want to get:

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


What I'm getting:

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



I want to remove just the comma that is between
}
and
]
, but I don't know how.




The code:


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 "]";





I've tried adding a
rtrim($locs, ",");
after the print, but it removes all the commas, and I need all of them except the last one.

Answer

I would do it storing the string in a variable.

When you finish adding values, you do the rtrim, and then add the square bracket and print it.

$myString = "[";
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.",";
    $myString .= $locs;
  }
  mysqli_free_result($result);
  $myString = rtrim($myString, ",");
}
$myString .= "]";

print $myString;
Comments