Jackosn5 Posted March 17, 2009 Share Posted March 17, 2009 My php code: while($row = mysql_fetch_array($result)) { $news = array('Artikel' => '{"Id":'.$row[id].',"LinkText":"'.$row[LinkText].'","Url":"'.$row.'","Title":"'.$row[Title].'"}'); foreach ($news as $key => $value) { if(!empty($value)){ $value = "$value, ". '<br>';} echo $value ; } } This is the output: {"Id":1,"LinkText":"Text","Url":"Text","Title":"Te xt"}, {"Id":2,"LinkText":"Text","Url":"Text","Title":"Te xt"}, {"Id":3,"LinkText":"Text","Url":"Text","Title":"Te xt"}, {"Id":4,"LinkText":"Text","Url":"Text","Title":"Te xt"}, //need to get rid of this comma Link to comment https://forums.phpfreaks.com/topic/149803-how-can-i-get-rid-of-the-last-comma-after-the-last-array-value/ Share on other sites More sharing options...
GingerRobot Posted March 17, 2009 Share Posted March 17, 2009 Couple of different approaches: 1.) Get a count of the records in the result set with mysql_num_rows. In the loop check to see if you are on the last row. Only echo the comma if you're not. 2.) Instead of echoing directly in the loop, either concatenate onto a string and then, outside the loop, extract everything except the last comma with substr or put everything into an array and use implode with a comma as the 'glue'. Link to comment https://forums.phpfreaks.com/topic/149803-how-can-i-get-rid-of-the-last-comma-after-the-last-array-value/#findComment-786633 Share on other sites More sharing options...
Jackosn5 Posted March 17, 2009 Author Share Posted March 17, 2009 Thank you, I solved the problem like this: while($row = mysql_fetch_array($result)) { $news[] = '{"Id":'.$row[id].',"LinkText":"'.$row[LinkText].'","Url":"'.$row.'","Title":"'.$row[Title].'"}'; } $news = implode (",", $news); print $news; Link to comment https://forums.phpfreaks.com/topic/149803-how-can-i-get-rid-of-the-last-comma-after-the-last-array-value/#findComment-786636 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.