开发者

String manipulation, removing a single comma

开发者 https://www.devze.com 2023-03-10 08:33 出处:网络
UPDATE 1: This is how I am attempting to build the string: header(\'Content-type:application/json\'); function getdata($the_query)

UPDATE 1:

This is how I am attempting to build the string:

header('Content-type:application/json');

function getdata($the_query)
{
    $connection = mysql_connect('server', 'user', 'pass') or die (mysql_error());
    $db = mysql_select_db('db_name', $connection) or die (mysql_error());

    $results = mysql_query($the_query) or die(mysql_error());

    $the_data = "{
            \"rss\": {
                \"channels\" : [
                    { 
                        \"title\" : \"".$title."\",
                        \"link\": \"http://www.mycompany.com/external.php\",
                        \"description\": \"company description goes here\",";

                        while($row = mysql_fetch_array($results))
                        {
                            extract($row);

                            $the_data .= "\"items\" : [
                                {
                                    \"title\": \"".$title."\",
                                    \"link\": \"".$link."\",
                                    \"guid\": \"".$link."\",
                                    \"pubDate\": \"".$date."\",
                                    \"description\": \"".$description."\"
                                } ],";
                        }   

                    $the_data .= "} ]
                }
                 }";

    mysql_close($connection);

    return $the_data;
}

ORIGINAL QUESTION:

I have a string similar to this:

$mystring = "{
      \"rss\": {
        \"channels\" : [
          { 
            \"title" : \"title goes here\",
            \"link": \"link goes here\",
            \"description": \"description goes here\",
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"d开发者_如何学JAVAata goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
         } ]
      }
    }";

How do I remove the last comma?


get the position of the reverse of the string first

stripos(',', strrev($myString))

then you can do whatever you want, replace it, delete it, up to you.


Instead of fixing the error you should fix the cause and don’t insert that last comma in the first place.

The best would be to build the data structure using PHP’s native data types and then use json_encode to convert it to a JSON data string:

function getdata($the_query)
{
    $connection = mysql_connect('server', 'user', 'pass') or die (mysql_error());
    $db = mysql_select_db('db_name', $connection) or die (mysql_error());

    $results = mysql_query($the_query) or die(mysql_error());
    $channel = array(
        'title'       => $title,
        'link'        => 'http://www.example.com/external.php',
        'description' => 'company description goes here',
        'items'       => array()
    );
    while ($row = mysql_fetch_array($results)) {
        $channel['items'][] = array(
            'title'       => $row['title'],
            'link'        => $row['link'],
            'guid'        => $row['link'],
            'pubDate'     => $row['date'],
            'description' => $row['description']
        );
    }
    mysql_close($connection);
    $data = array('rss' => array('channels' => array($channel)));
    return json_encode($data);
}


As mentioned in the comments, you might be approaching it the wrong way.

But if you really want to do it this way, the following will remove the last comma:

$mystring = preg_replace("/,(?![^,]*,)/",'',$mystring);


I would try and make it correct when you generate it.

I am doing it the only way I know, i.e. adding to a string using .= then looping through a database to get the bit which loops

from this comment it looks like you are just building the string yourself.

While in your loop, check which element in the array you are on and don't add the comma (forgive pseudocode nature of example)

$string .= item[i];
if($iterator < ($numberofitems-1){$string .=",";}

Obviously in your example above you will need to get the number of rows returned and check whether there are more to come on each loop.

Saying that, I would favour building the json with http://www.php.net/manual/en/function.json-encode.php


You could do:

$pos= strripos($mystring, ",");
$mystring[$pos]=" ";


To make as little modification as it is possible (lazy and wrong way) you could change the way $the_data string is created:

      $pieces = array();
      while($row = mysql_fetch_array($results))
                    {
                        extract($row);

                        $pieces[] = "\"items\" : [
                            {
                                \"title\": \"".$title."\",
                                \"link\": \"".$link."\",
                                \"guid\": \"".$link."\",
                                \"pubDate\": \"".$date."\",
                                \"description\": \"".$description."\"
                            } ]";
                    }   

                $the_data .= implode(',', $pieces);

but overall it is better rewrite whole chunk of your code according with answers above with use of json_encode function.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号