Reputation: 121
How can I remove the last character (,) of my output.
I tried several things, but none of them worked for me. This is my code:
$sql = "SELECT t_id, t_time, t_value FROM templogger";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$string = "[".$row["t_time"].", ".$row["t_value"]."],";
$trim = substr($string, 0, -1);
echo $trim;
}
Upvotes: 1
Views: 152
Reputation:
There may be a more elegant solution, but this should do the trick.
Replace:
while($row = $result->fetch_assoc()) {
echo "[".$row["t_time"].", ".$row["t_value"]."],";
}
With:
$z=0;
while($row = $result->fetch_assoc()) {
$row_array[$z] = "[".$row["t_time"].", ".$row["t_value"]."]";
$z++;
}
$z=0;
while($z < count($row_array)) {
if($z == count($row_array)-1) {
echo $row_array[$z];
} else {
echo $row_array[$z].',';
}
$z++;
}
Upvotes: 0
Reputation: 4833
$total = $result->num_rows;
$counter = 0;
while ($row = mysql_fetch_array($result)) {
echo '['.$row['t_time'].', '.$row['t_value'].']';
if (++$counter !== $total) {
echo ',';
}
}
Upvotes: 0
Reputation: 7896
Build your output, then echo it out once after removing the final comma.
$final = "";
while($row = $result->fetch_assoc()) {
$final .= "[".$row["t_time"].", ".$row["t_value"]."],";
}
$final = substr($final, 0, -1);
echo $final;
Upvotes: 2
Reputation: 32252
Don't output it in the first place.
Bruteforce:
$first = true;
while($row = $result->fetch_assoc()) {
if( !$first ) { echo ','; }
echo "[".$row["t_time"].", ".$row["t_value"]."]";
}
Implode:
$foo = [];
while($row = $result->fetch_assoc()) {
$foo[] = "[".$row["t_time"].", ".$row["t_value"]."]";
}
echo implode(',', $foo);
But if you're just trying to output JSON like @rotvulpix suggested then you shouldn't be trying to manually format it in the first place:
$foo = [];
while($row = $result->fetch_assoc()) {
$foo[] = [ $row["t_time"], $row["t_value"] ];
}
echo json_encode($foo);
Upvotes: 2