0

Hi I want JSON response in below format using PHP.

{
  "response": {
    "status": "ok",
    "results": [    
      {
        "id": "123",
        "fields": {
          "trailText": "SomeText",
          "thumbnail": "URL"
        },
        "tags": [
          {
            "id": "profile/amy-walker",
            "type": "contributor",
        ]
      }
  ]
  }
}

My PHP Code

while($row = mysqli_fetch_assoc($result1))
{
    $temp_array[$num_rows]['id']= $row["id"];
    //Some more code
}
echo $post = json_encode(array('response'=>$myObj,$temp_array));

But I got response like this

{
  "response": {
    "status": "ok"
    },
    "results": [    
      {
        "id": "123",
        "fields": {
          "trailText": "SomeText",
          "thumbnail": "URL"
        },
        "tags": [
          {
            "id": "profile/amy-walker",
            "type": "contributor",
        ]
      }
  ]
}

I want my array should be bound inside response.

$myObj is

object(stdClass)#4 (8) { 
    ["status"]=> string(2) "ok" 
    ["userTier"]=> string(9) "developer" 
    ["total"]=> int(8282) 
    ["startIndex"]=> int(1) 
    ["pageSize"]=> int(12) 
    ["currentPage"]=> int(1) 
    ["pages"]=> int(8282) 
    ["orderBy"]=> string(6) "newest" 
}
4
  • 2
    You could try json_encode(array('response'=>array($myObj,$temp_array))) to group together the last bits of data (i.e. add an extra array() in) Commented Apr 6, 2020 at 6:33
  • show us the value of $myObj by doing var_dump($myObj); Commented Apr 6, 2020 at 7:02
  • What have you tried to debug the problem? If json_encode produces a different output, then your input data is in the wrong format Commented Apr 6, 2020 at 8:32
  • @Nico Yes i have some issue with my end Nigel code worked for me. Commented Apr 6, 2020 at 9:09

1 Answer 1

1

Based on your comment regarding $myObj data. It seems @Nigel Ren code will work for you with a small modification.

do like this:

$result = array($myObj->status,$temp_array);

echo $post = json_encode(array('response'=>$result));
Sign up to request clarification or add additional context in comments.

Comments

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.