Reputation: 1339
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.
Upvotes: 0
Views: 58
Reputation: 656
This can be done using union operator also.
$requestBody = '{
"Key 1":"Value 1",
"Key 2":"Value 2",
"Key 3":"Value 3",
"Key 4":"Value 4"
}';
$json_create= json_decode($requestBody, true );
$other_array = [
"type" => "message",
"elements" => [],
"actions" => []
];
$final_json = $json_create + $other_array;
Upvotes: 1
Reputation: 1045
<?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"
}
Upvotes: 1
Reputation: 780871
Use array_merge
rather than putting the $json_create
inside the array.
$final_json = array_merge($json_create,
[
"type" => "message",
"elements" => $json_merge,
"actions" => $actions_json
]);
Upvotes: 2