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
JavaScript
x
{
"Key 1":"Value 1",
"Key 2":"Value 2",
"Key 3":"Value 3",
"Key 4":"Value 4"
}
That comes over file_get_contents
JavaScript
$requestBody = file_get_contents('php://input');
$json_create= json_decode($requestBody);
And this is the JSON I am creating
JavaScript
$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
JavaScript
{
"type": "message",
"elements": [
{
"msg_text": "This is a simple response message"
}
]
}
What I am trying to achieve is
JavaScript
{
"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
JavaScript
<?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
JavaScript
{
Key1: "Value 1",
Key2: "Value 2",
Key3: "Value 3",
Key4: "Value 4",
type: "message",
elements: "foo",
actions: "bar"
}