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 Quote Link to comment 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'. Quote Link to comment 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; Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.