Mo.
Mo.

Reputation: 27503

php string in to javascript code with comma except last string

I'm using a javascript plugin this is the line which I need help from u

<script type="text/javascript"> 
   $('ul#news').newswidget({ source: ['http://rss.news.yahoo.com/rss/us', 'http://rss.news.yahoo.com/rss/world', 'http://feeds.bbci.co.uk/news/rss.xml'],

I would like to add URL data from MySQL I'm using it with while loop like this

     $('ul#news').newswidget({ source:[<?php
while($rssrow = mysql_fetch_array($rss))
{
     echo "'"."$rssrow[rss_name]"."'".",";
}
?>],

It doesn't work properly :(. I need to get like URL,URL,RUL like this. that means no comma for the last one

any one please help me

Upvotes: 0

Views: 355

Answers (5)

Dmitry F
Dmitry F

Reputation: 1670

here is a little bit different approach:

<?php
$news = array(
'source' => array(
    'http://example.com',
    'http://example.com'
)
);
$news_json = json_encode($news);
?>

<script>
$('ul#news').newswidget(<?php echo $news_json; ?>);
</script>

another variation:

$url = array();
while($rssrow = mysql_fetch_array($rss))
{
    $url[] = '"' . $rssrow['rss_name'] . '"';
}
echo implode(',', $url);

Upvotes: 1

Adrian Heine
Adrian Heine

Reputation: 4141

I wonder why no comment points out that you should definitely escape your output. If an entry contains a ', all solutions aside from Dmitry F’s first will break badly.

$('ul#news').newswidget({ source:[<?php
$arr = array();
while($rssrow = mysql_fetch_array($rss))
{
  $arr[] = '"' . str_replace('"', '\"', $rssrow['rss_name']) . '"';
}
echo implode(',', $arr);
?>],

Upvotes: 1

user898741
user898741

Reputation:

$urls = "";

while($rssrow = mysql_fetch_array($rss))
{
    $urls.= "'$rssrow[rss_name]',";
}

echo substr($urls, 0, -1);

Upvotes: 1

cwallenpoole
cwallenpoole

Reputation: 82058

You can actually do that pretty easily by a simple reorganization:

if($rssrow = mysql_fetch_array($rss))
{
    echo "'".$rssrow['rss_name']."'";
    while($rssrow = mysql_fetch_array($rss))
    {
         // note no quotes -- they are redundant
         // prepend the comma
         echo ","."'".$rssrow['rss_name']."'";
    }
}

It does make for an extra step for the reader, but it does have the benefit of not needing substring, a new array, or a flag.

Upvotes: 3

NullUserException
NullUserException

Reputation: 85478

You could just build the string and remove the last comma:

$result = '';
while($rssrow = mysql_fetch_array($rss))
{
     $result .= "'"."$rssrow[rss_name]"."'".",";
}

echo ($result != '') ? substr($result, 0, -1) : "''";

OR use implode():

$result = array();
while($rssrow = mysql_fetch_array($rss))
{
     $result[] = $rssrow[rss_name];
}
echo "'" . implode($result, "','") . "'";

(both of these methods will output '' if the result set is empty.)

Upvotes: 2

Related Questions