lStoilov
lStoilov

Reputation: 1339

Append JSON code to a JSON created from MySQL and PHP

I am trying to create dynamically a JSON from a MySQL, which seems fairly easy with this piece of code I found in this thread Create nested json object using php mysql. However, I want to add before and after the $json_response some piece of JSON code.

The main code

    $result = mysql_query("SELECT * FROM Places "); 
$json_response = array(); //Create an array
while ($row = mysql_fetch_array($result))
{
    $row_array = array();
    $row_array['title'] = $row['title'];        
    $row_array['image_url'] = $row['image_url'];
    $row_array['subtitle'] = $row['subtitle'];      
    $row_array['buttons'] = array();
    $id = $row['id'];


    $option_qry = mysql_query("SELECT * FROM Places where id=$id");
    while ($opt_fet = mysql_fetch_array($option_qry))
    {
        $row_array['buttons'][] = array(
            'type' => $opt_fet['type'],
            'caption' => $opt_fet['caption'],
            'url' => $opt_fet['url'],
        );

    }
    array_push($json_response, $row_array); //push the values in the array
}

echo json_encode($json_response,  JSON_PRETTY_PRINT);

Produces this JSON

    [
        {
            "title": "Name of the place",
            "image_url": "image.jpg",
            "subtitle":Additional info",
            "buttons": [
                {
                    "type": "'url'",
                    "caption": "More Info",
                    "url": "https://some link "
                }
            ]
        },
        {
            "title": "Name of the place 2",
            "image_url": "image2.jpg",
            "subtitle":Additional info2",
            "buttons": [
                {
                    "type": "'url'",
                    "caption": "More Info",
                    "url": "https://some link 2"
                }
            ]
        }
    ] 

I have somehow to add the following code before the already created JSON

{
  "version": "v2",
  "content": {
    "messages": [
      {
        "type": "cards",
        "elements":

And this code in the end

      }
    ]
  }
}

Upvotes: 1

Views: 93

Answers (2)

Blue
Blue

Reputation: 22911

Pretty simple:

$final_json = [
    "version" => "v2",
    "content" => [
        "messages" => [[
            "type" => "cards",
            "elements" => $json_response
        ]]
    ]
];

echo json_encode($final_json, JSON_PRETTY_PRINT);

Personally, I'd rename $json_response to $messages for clarity purposes.

Upvotes: 3

Chintan7027
Chintan7027

Reputation: 7615

While declaring array $json_response = array(); you can actually prepare it with your default values require like

$stdObj=new \stdClass();
$stdObj->version="V2";
$stdObj->content=(object)["messages"=>(object)["type"=>'cards','elements'=>$row_array['buttons']]];

echo json_encode($stdObj, JSON_PRETTY_PRINT);

Upvotes: 1

Related Questions