0

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);
4
  • rtm explode Commented Apr 16, 2022 at 17:11
  • Can You answer it please ? I'm new to php. Commented Apr 16, 2022 at 17:13
  • 1
    Your friend stackoverflow.com/questions/71895723/…? Commented Apr 16, 2022 at 17:20
  • @u_mulder maybe one of them is the sender and the other is the receiver? Really it looks like AbhishekJoshi there was tasked with inserting that response into an input field, and so Rahul FYI, make sure you coordinate these devops with Joshi so you have your API spec clear and don't have to be converting stuff all over again. Commented Apr 16, 2022 at 18:59

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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)),

4 Comments

tags is a string in this format tag1, tag2, tag3 and i can't make changes in this.
updated my answer to include the simple split. Basically you need your variable to become an array to get the result you want. You might need to trim and do other processing too. preg_split lets you put in regex to handle the whitespace. With explode you can use an arraymap
Or simply preg_split ('/,\s*/', to strip white-space if it exists.
Agreed. It's much better to use an asterisk as you may not know what you are getting (unless you get to write that other bit of code).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.