building a php array that will make specific JSON - php

I need to generate the following JSON:
{
"title": "my form",
"fields": [
{
"type": "short_text",
"question": "What is your name?"
},
{
"type": "multiple_choice",
"question": "How often do you want to receive emails?",
"choices": [
{
"label": "Daily"
},
{
"label": "Weekly"
},
{
"label": "Monthly"
},]
},]
I'm trying to do it with this php code:
$data = array(
"title" => "my form",
"fields" => array (
array (
"type" => "short_text",
"question" => "What is your name?"
),
array (
array (
"type" => "multiple_choice",
"question" => "How often do you want to receive emails?",
"choices" => (
array ("label" => "Daily")
),
(array ("label" => "Weekly")),
(array ("label" => "Monthly"))
)
)
)
);
$output = json_encode($data);
...but it's not working.
I'd appreciate any help you guys can offer!

<?php
$data = array (
'title' => 'my form',
'fields' =>
array (
array (
'type' => 'short_text',
'question' => 'What is your name?',
),
array (
'type' => 'multiple_choice',
'question' => 'How often do you want to receive emails?',
'choices' =>
array (
array (
'label' => 'Daily',
),
array (
'label' => 'Weekly',
),
array (
'label' => 'Monthly',
),
),
),
),
);
$output = json_encode($data);
?>

Related

Push nested element into multidimensional array [duplicate]

This question already has answers here:
How to add elements to an empty array in PHP?
(8 answers)
Push Array inside an Array PHP
(2 answers)
Closed 28 days ago.
I have this array
echo '<script type="application/ld+json">';
$data = array(
'#context' => 'https://schema.org',
'#graph' => array(),
);
$data['#graph'][] = [
"#type" => "ImageObject",
];
$data['#graph'][] = [
"#type" => "BreadcrumbList",
"itemListElement" => array(),
];
print_r(json_encode($data));
echo "</script>";
Now I want to add another array "itemListElement" inside the last $data['#graph'][] and print but don't know how to go about it.
am expecting
{
"#type": "BreadcrumbList",
"#id": "http:\/\/localhost\/#breadcrumb",
"itemListElement": [{
"#type": "ListItem",
"position": "1",
"item": {
"#id": "http:\/\/localhost",
"name": "Home"
}
}, {
"#type": "ListItem",
"position": "1",
"item": {
"#id": "link 2",
"name": "Home"
}
}]
}
You're referring to nested arrays.
echo '<script type="application/ld+json">';
$data['#graph'][] = [
'#type' => 'BreadcrumbList',
'#id' => "http:\/\/localhost\/#breadcrumb",
'itemListElement' => [
[
'#type' => 'ListItem',
'position' => '1',
'item' => [
'#id' => "http:\/\/localhost",
'name' => 'Home'
]
],
[
'#type' => 'ListItem',
'position' => '2',
'item' => [
'#id' => 'link 2',
'name' => 'Home'
]
]
]
];
print_r(json_encode($data));
echo "</script>";
Good luck on your test
<?php
// PHP program to creating two
// dimensional associative array
$marks = array(
// Ankit will act as key
"Ankit" => array(
// Subject and marks are
// the key value pair
"C" => 95,
"DCO" => 85,
"FOL" => 74,
),
// Ram will act as key
"Ram" => array(
// Subject and marks are
// the key value pair
"C" => 78,
"DCO" => 98,
"FOL" => 46,
),
// Anoop will act as key
"Anoop" => array(
// Subject and marks are
// the key value pair
"C" => 88,
"DCO" => 46,
"FOL" => 99,
),
);
echo "Display Marks: \n";
print_r($marks);
?>
**Output:**
Display Marks:
Array
(
[Ankit] => Array
(
[C] => 95
[DCO] => 85
[FOL] => 74
)
[Ram] => Array
(
[C] => 78
[DCO] => 98
[FOL] => 46
)
[Anoop] => Array
(
[C] => 88
[DCO] => 46
[FOL] => 99
)`enter code here`
)

UnableToDeserializePostBody when trying to create a teams meeting with php Microsoft Graph Api

Calling Graph API endpoint
POST https://graph.microsoft.com/v1.0/me/events
resulted in a 400 Bad Request with response:
{
"error": {
"code":"UnableToDeserializePostBody",
"message":"were unable to deserialize..."
}
}
This is my code:
$token = GraphHelper::getUserToken();
GraphHelper::$userClient->setAccessToken($token);
$CreateMeetingBody =
array(
'message' => array (
'subject' => 'Test afspraak Marloes',
'body' => array (
'content' => 'Does morning work for you?',
'contentType' => 'HTML'
),
'start' => array (
'dateTime' => '2022-07-17T18:00:00',
'timeZone' => 'Europe/Paris'
),
'end' => array (
'dateTime' => '2022-07-17T19:00:00',
'timeZone' => 'Europe/Paris'
),
'location' => array (
'displayName' => 'Microsoft Teams',
),
'attendees' => array (
array (
'emailAddress' => array (
'address' => 'stijnd0413#icloud.com',
'name' => 'Stijn Deckers'
),
'type' => 'required'
)
),
'allowNewTimeProposals' => false,
'isOnlineMeeting' => true,
)
);
$headers = [
'Content-Type' => 'application/json',
];
header('Content-Type: application/json; charset=utf-8');
$CreateMeetingJSON = json_encode($CreateMeetingBody);
GraphHelper::$userClient->createRequest('POST', '/me/events')
->attachBody($CreateMeetingJSON)
->addHeaders(['Content-Type' => 'application/json',])
->execute();
'''
The rest of the code works and I am able to authenticate.
Remove message object from $CreateMeetingBody and keep its content only.
$CreateMeetingBody =
array(
'subject' => 'Test afspraak Marloes',
'body' => array (
'content' => 'Does morning work for you?',
'contentType' => 'HTML'
),
'start' => array (
'dateTime' => '2022-07-17T18:00:00',
'timeZone' => 'Europe/Paris'
),
'end' => array (
'dateTime' => '2022-07-17T19:00:00',
'timeZone' => 'Europe/Paris'
),
'location' => array (
'displayName' => 'Microsoft Teams',
),
'attendees' => array (
array (
'emailAddress' => array (
'address' => 'stijnd0413#icloud.com',
'name' => 'Stijn Deckers'
),
'type' => 'required'
)
),
'allowNewTimeProposals' => false,
'isOnlineMeeting' => true
);
Now json_encode($CreateMeetingBody) will produce the correct json body
{
"subject": "Test afspraak Marloes",
"body": {
"content": "Does morning work for you?",
"contentType": "HTML"
},
"start": {
"dateTime": "2022-07-17T18:00:00",
"timeZone": "Europe/Paris"
},
"end": {
"dateTime": "2022-07-17T19:00:00",
"timeZone": "Europe/Paris"
},
"location": {
"displayName": "Microsoft Teams"
},
"attendees": [
{
"emailAddress": {
"address": "stijnd0413#icloud.com",
"name": "Stijn Deckers"
},
"type": "required"
}
],
"allowNewTimeProposals": false,
"isOnlineMeeting": true
}

How to create json array php with childs

i am struggling with encoding json data
when posting to confluenec it needs to be
{"id":"282072112","type":"page","title":"new page","space":{"key":"BLA"},"body":{"storage":{"value":"<p>This is the updated text for the new page</p>","representation":"storage"}},"version":{"number":2}}'
so in php i created
$data = array('id'=>$siteid, 'type'=>'page', 'title'=>'title of the page');
$data_json = json_encode($data);
print_r ($data_json);
The endresult should look like
{
"id": "282072112",
"type": "page",
"title": "new page",
"space": {
"key": "BLA"
},
"body": {
"storage": {
"value": "<p>This is the updated text for the new page</p>",
"representation": "storage"
}
},
"version": {
"number": 2
}
}
but how can i add the childs etc?
Thanks
You can nest data in arrays similarly to what you would to in JavaScript:
$data = [
'id' => $siteid,
'type' => 'page',
'title' => 'new page',
'space' => [
'key' => 'BLA',
],
'body' => [
'storage' => [
'value' => '<p>...</p>',
'representation' => 'storage'
],
],
'version' => [
'number' => 2,
],
];
// as JSON in one line:
echo json_encode($data);
// or pretty printed:
echo json_encode($data, JSON_PRETTY_PRINT);
$data = [
"id" => $siteid,
"type" => "page",
"space" => ["key" => "bla"]
//...
]
You can nest arrays.
See also: Shorthand for arrays: is there a literal syntax like {} or []? and https://www.php.net/manual/en/language.types.array.php
Try it
$data_child = array( 'value'=> 'blablabla' );
$data = array('id'=>$siteid, 'type'=>'page', 'title'=>'title of the page', 'child' => $data_child );
$data_json = json_encode($data);
You can create nested array this way and the send it after json_encode()
<?php
$preparing_array = array
(
"id" => 282072112,
"type" => "page",
"title" => "new page",
"space" => array
(
"key" => "BLA"
),
"body" => array
(
"storage" => array
(
"value" => "<p>This is the updated text for the new page</p>",
"representation" => "storage"
)
),
"version" => array
(
"number" => 2
)
);
echo json_encode($preparing_array, JSON_PRETTY_PRINT);
?>
DEMO: https://3v4l.org/16960

Message formatting, send buttons via Slack API with PHP

I'm using webhooks to send messages via Slack API
I need to send a button with a link to a report
I did it with Python successfully
But with PHP i'm having trouble with the arrays of actions in the attachments
code 1
$data = array(
"text" => $message
);
$actions =
[
'type' => "button",
'text' => "Report1",
'url' => "https://url.report1"
];
$data += [
"attachments" =>
[
"fallback" => "More details...", //I only get the message and this text in the slack
'actions' => [$actions] // or array($actions)
]
];
$payload = json_encode($data);
print_r($data) output:
Array
(
[text] => teste
[attachments] => Array
(
[fallback] => More details...
[actions] => Array
(
[0] => Array
(
[type] => button
[text] => Report1
[url] => https://url.report1
)
)
)
)
The paylod is shown, but the button doesn't
code 2
$data = array(
"text" => $message
);
$actions =
[
'type' => "button",
'text' => "Report1",
'url' => "https://url.report1"
];
$data += [
"attachments" =>
[
"fallback" => "More details...",
'actions' => $actions
]
];
$payload = json_encode($data);
print_r($data) output:
Array
(
[text] => teste
[attachments] => Array
(
[fallback] => More details...
[actions] => Array
(
[type] => button
[text] => Report1
[url] => https://url.report1
)
)
)
Neither payload or button are showed
Here's the documentation example, it's very easy to send this with python
{
"text": "<#W1A2BC3DD> approved your travel request. Book any airline you like by continuing below.",
"attachments": [
{
"fallback": "Book your flights at https://flights.example.com/book/r123456",
"actions": [
{
"type": "button",
"text": "Book flights 🛫",
"url": "https://flights.example.com/book/r123456"
}
]
}
]
}
How I can create this kind of structure in PHP?
Here is your "code 1" with the correction. Your attachments property needs to be an array of attachment arrays. You only had a simple array.
$message = "Hello Stackoverflow";
$data = array(
"text" => $message
);
$actions =
[
'type' => "button",
'text' => "Report1",
'url' => "https://url.report1"
];
$data += [
"attachments" =>
[
[
"fallback" => "More details...", //I only get the message and this text in the slack
'actions' => [$actions] // or array($actions)
]
]
];
$payload = json_encode($data);
print_r($payload);
The resulting payload works in the message builder.

converting multidimensional array into json

this is my multidimensional array..i know how to encode array to json but not getting actual json expected json result
array (
1 =>
array (
'text' => 'Dashboard',
'spriteCssClass' => 'rootfolder',
'expanded' => 'true',
'id' => '1',
'item_name' => 'Dashboard',
'menu_type' => 'item',
'parent' => '0',
'items' =>
array (
9 =>
array (
'text' => 'Application',
'spriteCssClass' => 'html',
'id' => '9',
'item_name' => 'Application',
'menu_type' => 'header',
'parent' => '1',
'items' =>
array (
),
),
),
),
)
after encoding it into json i am getting the following result
for encodin i used json_encode($array);
{
"1": {
"text": "Dashboard",
"spriteCssClass": "rootfolder",
"expanded": "true",
"id": "1",
"item_name": "Dashboard",
"menu_type": "item",
"parent": "0",
"items": {
"9": {
"text": "Application",
"spriteCssClass": "html",
"id": "9",
"item_name": "Application",
"menu_type": "header",
"parent": "1",
"items": {}
}
}}}
i want the following encoded json
{
"text": "Dashboard",
"spriteCssClass": "rootfolder",
"expanded": "true",
"id": "1",
"item_name": "Dashboard",
"menu_type": "item",
"parent": "0",
"items": [
{
"text": "Application",
"spriteCssClass": "html",
"id": "9",
"item_name": "Application",
"menu_type": "header",
"parent": "1",
"items": {}
}]
}
i tried almost everything but not getting my expected json result
i want remove the array indexing from json like "1" { and also want to add "[" this after every items: column
It looks like you just want to json_encode($yourData[1]) instead of just json_encode($yourData)...
Your array is not 0 indexed, therefore json_encode assumes its an assoc array.
If you 0 index your array, you should get the expected result, or maybe even remove the index assignment completelely:
array (
array (
'text' => 'Dashboard',
'spriteCssClass' => 'rootfolder',
'expanded' => 'true',
'id' => '1',
'item_name' => 'Dashboard',
'menu_type' => 'item',
'parent' => '0',
'items' =>
array (
9 =>
array (
'text' => 'Application',
'spriteCssClass' => 'html',
'id' => '9',
'item_name' => 'Application',
'menu_type' => 'header',
'parent' => '1',
'items' =>
array (
),
),
),
),
)
EDIT***
to remove all numerical indexes / convert all "non-assoc" to normal use:
function normaliseArray($arr,$recurse=True) {
if (!is_array($arr))
return $arr;
if (count(array_filter(array_keys($arr), 'is_numeric')) == count($arr))
$arr = array_values($arr);
if ($recurse) {
foreach($arr as $k => $a) {
$arr[$k] = normaliseArray($a,$recurse);
}
}
return $arr;
}
json_encode(normaliseArray($array));
try that.
json_encode will encode it as is. The best you can do is force the array to start at 0 which would be the same as []:
$array = array_values($array);
$array[0]['items'] = array_values($array[0]['items']);

Categories