How to create json array php with childs - php

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

Related

How to JSON encode multi-dimensional array?

I am creating a array for posting candidate details to an API.
that API accepts data in JSON format, I am creating a data for the API using PHP array and using JSON encode to convert it JSON array. but not able to get intended format
PHP Code
$postArray = array(
"DefaultCurrency" => "USD",
"UserName" => "data",
"Photograph" => "data",
"PhotographThumb" => "data",
"Group" => "data",
"Summary" => "data",
"ResumeText" => "data",
"RollupListMembership" => array(
"RollupCode" => "data"
),
"CustomFields" => array(
"FieldName" => "Major",
"Values" => array(
$finalResumeData-> "data"
),
"FieldName" => "Years of Experience",
"Values" => array(
$MonthsOfWorkExperience
),
"FieldName" => "Executive Type",
"Values" => array(
$finalResumeData-> "data"
),
)
);
If i run this code as it is its showing only last result of the CustomFields
I have tried using array() for individual CustomFields in the array like
"CustomFields" => array(
array("FieldName" => "Major",
"Values" => array(
$finalResumeData-> "data"
)),
I am getting the results as
CustomFields: {
"0": {
"FieldName" : "Value",
"Values": ["data"]
}
}
Intended result
"CustomFields": [
{
"FieldName": "string",
"FieldType": "string",
"Values": [
"string"
]
},
{
"FieldName": "string",
"FieldType": "string",
"Values": [
"string"
]
}
],
So what should I update in the PHP array to get intended results.
Inside "CustomFields" you're repeating the same keys again within one array, so they will just overwrite each other. Instead you need an array of separate objects (represented by associative arrays in PHP), i.e. just the same structure as you've shown in your desired JSON output.
"CustomFields" => array(
array(
"FieldName" => "Major",
"Values" => array(
$finalResumeData->data
)
),
array(
"FieldName" => "Years of Experience",
"Values" => array(
$MonthsOfWorkExperience
)
),
array(
"FieldName" => "Executive Type",
"Values" => array(
$finalResumeData->data
)
),
)
N.B. This assumes you're using json_encode($postArray); without any extra options.
Demo: https://eval.in/1059736
I have just modified your code little bit and getting the output you wanted.
$postArray = array(
"DefaultCurrency" => "USD",
"UserName" => "data",
"Photograph" => "data",
"PhotographThumb" => "data",
"Group" => "data",
"Summary" => "data",
"ResumeText" => "data",
"RollupListMembership" => array(
"RollupCode" => "data"
),
"CustomFields" => array(
array("FieldName" => "Major",
"Values" => array(
'dsadas'=> "data"
)),
array("FieldName" => "Years of Experience",
"Values" => array(
'rewrew'=>'dsa'
)),
array("FieldName" => "Executive Type",
"Values" => array(
'test'=> "data"
)),
)
);
echo "<pre>";print_r($postArray);
echo json_encode($postArray);
?>
Here is the output I am getting.
{
"DefaultCurrency":"USD",
"UserName":"data",
"Photograph":"data",
"PhotographThumb":"data",
"Group":"data",
"Summary":"data",
"ResumeText":"data",
"RollupListMembership":{
"RollupCode":"data"
},
"CustomFields":[
{
"FieldName":"Major",
"Values":{
"dsadas":"data"
}
},
{
"FieldName":"Years of Experience",
"Values":{
"rewrew":"dsa"
}
},
{
"FieldName":"Executive Type",
"Values":{
"test":"data"
}
}
]
}

Dynamically push arrays into multidimensional array

I'm trying to dynamically build an array for the Facebook Messenger SDK and populate it with data from a database.
I can't seem to get a properly structured array no matter what I try.
What I need:
$messages = [
"attachment" => [
"type" => "template",
"payload" => [
"template_type" => "generic",
"elements" => [[
"title" => $row['title'],
"item_url" => $row['item_url'],
"image_url" => $row['image_url'],
"subtitle" => $row['subtitle'],
"buttons" => [[
"type" => "web_url",
"url" => "www.google.com",
"title" => "View Website"],
["type" => "postback",
"title" => "Start Chatting",
"payload" => "start"]]
]
]]
]];
I need to create the data inside buttons based on what I have in the database, tried with array_merge and inserting the array as a string:
// Created arrays
if (!empty($row['button1_type'])) {
$buttons[] = array("type" => $row['button1_type'],"url" => $row['button1_url'],
"title" => $row['button1_title'],
"payload" => $row['button1_payload']);
}
if (!empty($row['button2_type'])) {
$buttons[] = array("type" => $row['button2_type'],"url" => $row['button2_url'],
"title" => $row['button2_title'],
"payload" => $row['button2_payload']);
}
// In the case when I had array_merge - $buttons were actually named as $buttons1 and $buttons2
$buttons = array_merge($buttons1, $buttons2);
// Tried to add it as a string
if (!empty($row['button2_type'])) {
$buttons = "\"type\" => ".$row['button2_type'].",\"url\" => .".$row['button2_url'].",
\"title\" => ".$row['button2_title'].",
\"payload\" => ".$row['button2_payload'];
}
$messages = [
"attachment" => [
"type" => "template",
"payload" => [
"template_type" => "generic",
"elements" => [[
"title" => $row['title'],
"item_url" => $row['item_url'],
"image_url" => $row['image_url'],
"subtitle" => $row['subtitle'],
"buttons" => [
$buttons
]
]
]]
]];
Screenshot showing the differences between correct and incorrect:
So basically $buttons are created inside an extra array, how can I get rid of it? Maybe I should change the whole approach?
With
"buttons" => [$buttons]
//new array ^ ^
a new array is being created with square brackets so to avoid it. use
"buttons" => $buttons

return only duplicated values in multidimentional array php

I want to get only duplicated records in multidimentional array.
My array looks like:
"items": [
{
"id": "1",
"father_name": "YYY",
"surname": "XXX",
"name": "abc",
},
{
"id": "1",
"father_name": "YYY",
"surname": "XXX",
"name": "abc",
},
{
"id": "2",
"father_name": "ZZZ",
"surname": "UUU",
"name": "abc",
},
]
I want to get results like
"items": [
{
"id": "1",
"father_name": "YYY",
"surname": "XXX",
"name": "abc",
},
]
How can I get it? Please help me I am stuck here.
I have tried many things but everything works in single dimensional array
Thanks in advance!
As an alternative to other answers you could also do something like:
$duplicates = [];
while ($a = array_shift($array)) {
if (in_array($a, $array) && !in_array($a, $duplicates)) {
$duplicates[] = $a;
}
}
Hope this helps!
The given data is a json string.
Assuming the same for your array structure try this:
$arr = array("items"=>array(
"id"=> "1",
"father_name"=> "YYY",
"surname"=> "XXX",
"name"=> "abc",
),
array(
"id"=> "1",
"father_name"=> "YYY",
"surname"=> "XXX",
"name"=> "abc",
),
array(
"id"=> "2",
"father_name"=> "ZZZ",
"surname"=> "UUU",
"name"=> "abc",
)
);
$withoutDuplicates = array_unique($arr, SORT_REGULAR);
$duplicates = array_diff_assoc($arr, $withoutDuplicates);
echo "<pre>";
print_r($duplicates);
OUTPUT:
Array
(
[0] => Array
(
[id] => 1
[father_name] => YYY
[surname] => XXX
[name] => abc
))
<?php
$arr = array(
'items' => array(
0 => array(
'id' => '1',
'father_name' => 'YYY',
'surname' => 'XXX',
'name' => 'abc'
),
1 => array(
'id' => '1',
'father_name' => 'YYY',
'surname' => 'XXX',
'name' => 'abc'
),
2 => array(
'id' => '2',
'father_name' => 'ZZZ',
'surname' => 'UUU',
'name' => 'abc'
)
)
);
$result = array();
for ($i = 0; $i < count($arr['items'])-1; $i++) {
for ($x = $i+1; $x < count($arr['items']); $x++) {
if ($arr['items'][$i] !== $arr['items'][$x] || in_array($arr['items'][$i], $result))
continue;
array_push($result, $arr['items'][$i]);
}
}
print_r($result);
?>
One way to go at it, assuming you are working with multi-dimensional php arrays.
You can do something like this:
foreach($items as $key => $item)
{
unset($items[$key]);
if(array_search($item['id'], array_column($items, 'id_or_another_key')))
{
$result[] = $item;
}
}
The sense of this code is next:
You should go through the initial array in the cycle
Delete the current item from the array
Search the similar items by the 'id' value or by the another key between the rest elements
If the item was found, you put it to the result array with duplicated items.
<?php
/**
* #param $data array
*
* #return array
*/
function getDuplicatesOnly(array $data): array
{
$result = [
'items' => [
],
];
foreach ($data as $key => $datum) {
$itemId = $datum['id'];
unset($data[$key]);
$columns = array_column($data, 'id');
if(in_array($itemId, $columns)) {
$result['items'][] = $datum;
}
}
return $result;
}
$testData = [
'input' => [
'items' => [
[
'id' => '1',
'father_name' => 'YYY',
'surname' => 'XXX',
'name' => 'abc'
],
[
'id' => '1',
'father_name' => 'YYY',
'surname' => 'XXX',
'name' => 'abc'
],
[
'id' => '2',
'father_name' => 'ZZZ',
'surname' => 'UUU',
'name' => 'abc'
]
]
],
'output' => [
'items' => [
[
'id' => '1',
'father_name' => 'YYY',
'surname' => 'XXX',
'name' => 'abc'
]
],
],
];
$output = getDuplicatesOnly($testData['input']['items']);
assert($testData['output'] == $output, "Failed asserting data.");
Can be tested here.

building a php array that will make specific JSON

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);
?>

Insert an array to a specified location in named array

In the array below, how can I push the new array into the $options array at the specified location?
$options = array (
array( "name" => "My Options",
"type" => "title"),
array( "type" => "open"),
array("name" => "Test",
"desc" => "Test",
"id" => $shortname."_theme",
"type" => "selectTemplate",
"options" => $mydir ),
//I want the pushed array inserted here.
array("name" => "Test2",
"desc" => "Test",
"id" => "test2",
"type" => "test",
"options" => $mydir ),
array( "type" => "close")
);
if(someCondition=="met")
{
array_push($options, array( "name" => "test",
"desc" => "description goes here",
"id" => "testMet",
"type" => "checkbox",
"std" => "true"));
}
You can use array_splice. For your example:
if($some_condition == 'met') {
// splice new option into array at position 3
array_splice($options, 3, 0, array($new_option));
}
Note: array_splice expects the last parameter to be an array of new elements, so for your example you need to pass an array containing the new option's array.
Simply
array_splice($options, 3, 0, $newArr);
for insert a new array, not to a spesific location(between $r[4] and $r[5]):
$options[]=array ("key" => "val"); //insert new array
$options[]=$v; //insert new variable
to insert a new array after spesific variable:
function array_push(&$array,$after_element_number,$new_var)
{
array_splice($array, $after_element_number, 0, $new_var);
}
if(someCondition=="met")
{
array_push($options, 2, array( "name" => "test",
"desc" => "description goes here",
"id" => "testMet",
"type" => "checkbox",
"std" => "true"));
}
As connec says, you can use array_splice, but without forgetting to wrap your array in another array, like this:
if ('met' === $some_condition)
{
array_splice($options, 3, 0, array(array(
'name' => 'test',
'desc' => 'description goes here',
'id' => 'testMet',
'type' => 'checkbox',
'std' => 'true'
)));
}
Edit: connec has already specified its response.

Categories