Home > Enterprise >  How to make json format like that?
How to make json format like that?

Time:04-17

I Need json response in this format {"tgas": ["tag1", "tag2" , "tag3"]}. But currenly it returns this in response. ``` {"title":"Post Title", "tgas":"tag1,tag2,tag3"}. Here is my php code

<?php
$response = array(
            'title' => $title,
            'plot'=> strip_tags($description),
            'storline'=> strip_tags($storyline),
            'tgas'=> ($tagsoutput) //"tgas":"tag1,tag2,tag3"
            );
            $rt = json_encode($response, true);

CodePudding user response:

this is the way to do it:

<?php
$response = array(
              'title' => $title,
              'plot'=> strip_tags($description),
              'storline'=> strip_tags($storyline),
              'tgas'=> explode(',', $tagsoutput)
            );
            $rt = json_encode($response, true);

CodePudding user response:

<?php   
        $response = array(
        'title' => $title,
        'plot'=> strip_tags($description),
        'storline'=> strip_tags($storyline),
        'tgas'=> ["tag1","tag2","tag3"]
        );
        $rt = json_encode($response, true);

CodePudding user response:

The issue is likely how you are adding tagsoutput which is not visible in your example. It should be something like this:

$tagsoutput = array("tag1","tag2");

If $tagsoutput is defined already then you can split the string inline:

'tgas'=> preg_split ("/,/", $tagsoutput),

with trailing whitespace:

'tgas'=> preg_split ("/,\s/", $tagsoutput),

OR

if there is never whitespace:

'tgas'=> explode (",", $tagsoutput),

to trim whitespace:

'tgas'=> array_map('trim',explode (",", $tagsoutput)),

  •  Tags:  
  • php
  • Related