Skip to content
Advertisement

Add JSON keys/values while creating another JSON PHP

I am trying to pass some JSON keys/values that I have to another JSON I am creating dynamically.

For example, this is the JSON I have in $json_create

{
"Key 1":"Value 1",
"Key 2":"Value 2",
"Key 3":"Value 3",
"Key 4":"Value 4"
}

That comes over file_get_contents

$requestBody = file_get_contents('php://input');
$json_create= json_decode($requestBody);

And this is the JSON I am creating

$final_json = [
       $json_create,
       "type" => "message",
       "elements" => $json_merge,  
       "actions" => $actions_json
  ];

echo json_encode($final_json, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);

Which print something like

{
  "type": "message",
  "elements": [
    {
      "msg_text": "This is a simple response message"
    }
  ]
}

What I am trying to achieve is

{
    "Key 1":"Value 1",
    "Key 2":"Value 2",
    "Key 3":"Value 3",
    "Key 4":"Value 4",
    "type": "message",
    "elements": [
        {
          "msg_text": "This is a simple response message"
     }
   ]
 }

There is quite a lot on that subject but somehow I could not succeed in implementing it.

Advertisement

Answer

<?php

$json_create = '{"Key1": "Value 1", "Key2": "Value 2", "Key3": "Value 3", "Key4": "Value 4"}';
$json_create = (array) json_decode($json_create);

$your_array = [
  "type" => "message",
  "elements" => 'foo',
  "actions" => 'bar'
];

$final_json = array_merge($json_create, $your_array);

$result = json_encode($final_json);


echo $result;

output

{
  Key1: "Value 1",
  Key2: "Value 2",
  Key3: "Value 3",
  Key4: "Value 4",
  type: "message",
  elements: "foo",
  actions: "bar"
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement