简体   繁体   中英

How to get Json response from PHP which have Object and Array and Json array present inside Json Object

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" 
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM