user11626808
user11626808

Reputation:

How do I remove the last comma of SQL array?

How do I remove the last comma on this array? I'm using SQL in this code.

<?php
$no=1;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
?>                            
{lat: <?php echo $row['lat'] ?>, 
lng: <?php echo $row['lng'] ?>},
<?php
}
?>

I expect the output to be:

{lat: -7.0476101, lng: 112.7323577}, {lat: -7.0319093, lng: 112.7614287}, {lat: -7.0433001, lng: 112.7606889}, {lat: -7.0459718, lng: 112.7583679} //last comma doesnt exist

But the result is:

{lat: -7.0476101, lng: 112.7323577}, {lat: -7.0319093, lng: 112.7614287}, {lat: -7.0433001, lng: 112.7606889}, {lat: -7.0459718, lng: 112.7583679}, //last comma exists

Thanks for your help

Upvotes: 1

Views: 160

Answers (4)

suman das
suman das

Reputation: 367

<?php
$count = $stmt->rowCount();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
?>                            
{lat: <?php echo $row['lat'] ?>, 
<?php if( $count == $rows ) { ?>
   lng: <?php echo $row['lng'] ?>}
 <?php }else{ ?>
lng: <?php echo $row['lng'] ?>},
<?php } ?>

<?php
}
?>

Upvotes: 0

user2182349
user2182349

Reputation: 9782

You may also be able to use:

$json = json_encode($stmt->fetchAll(PDO::FETCH_OBJ));

Ref: https://www.php.net/manual/en/pdostatement.fetchall.php

To help you see what is happening, start with:

var_dump($stmt->fetchAll(PDO::FETCH_OBJ));

that will show you what is returned from fetchAll

You want to see an array of object, or an array of associative arrays

Next use:

echo json_encode($stmt->fetchAll(PDO::FETCH_OBJ));

this will show you exactly what is produced

Upvotes: 0

Dhanushka sasanka
Dhanushka sasanka

Reputation: 528

That issue in your php application not MYSQL so

Try this one

<?php
$no=1;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
?>                            
<?php
}
?>
lat: <?php echo $row['lat'];?> 
lng: <?php echo $row['lng'];?>

<?php
}
?>

or Try this way from your code

<?php
$no=1;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
?>                            
{lat: <?php echo $row['lat'] ?>, 
lng: <?php echo $row['lng'] ?>},
<?php
}
?>
$tempRow =rtrim($row,',');

<?php
echo $tempRow; 
?>

rtrim($row,',') function removes your last ' , '

Upvotes: 0

Tim Morton
Tim Morton

Reputation: 2644

If you're just wanting to see the output formatted this way, the easiest way is to store the results as an array, and use join or implode to put it together as a string:

<?php

$result = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
  $result[] = sprintf("{lat:%s, lng:%s}",
              $row['lat'],
              $row['lng']
              );
}

echo join(', ',$result);
// or,
?>

<!-- if you're sticking this in a web page... ->
<?= join(', ',$result) ?>

using json_encode is even easier:

<?php
$no=1;
$result = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
  $result[] = array($row['lat'] => $row['lng']);
}

print json_encode($result);

?>

Upvotes: 1

Related Questions