How to JSON encode multi-dimensional array? - php

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"
}
}
]
}

Related

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

Correct Logic for PHP Array

I need to produce an output like this:
{
"properties": [
{
"name": "name",
"value": "A company name"
},
{
"name": "description",
"value": "A company description"
}
]
}
And i've written the logic as such:
$data = array(
"properties" => array(
"name" => "name",
"value" => $companyname,
"name" => "address",
"value" => $AddressLine1,
"name" => "address2",
"value" => $AddressLine2,
"name" => "address3",
"value" => $AddressLine3,
"name" => "locality",
"value" => $Locality,
"name" => "city",
"value" => $Town,
"name" => "state",
"value" => $County,
"name" => "zip",
"value" => $PostCode,
"name" => "country",
"value" => $Country,
"name" => "phone",
"value" => $Telephone,
"name" => "domain",
"value" => $Website,
"name" => "lead_forensics_business_id",
"value" => $hubspotcompanyid
)
);
Can someone highlight the correct way to produce the above output?
Each name and value pair should be their own arrays. Like this:
$data = [
"properties" => [
[
"name" => "name",
"value" => $companyname,
],
[
"name" => "address",
"value" => $AddressLine1,
],
// And so on
]
];
(I've opted for the shorthand version of creating arrays [] instead of array() since it's, in my opinion, easier to read).
This should do the trick if i remember correctly:
$data = array(
"properties" => array(
array(
"name" => "name",
"value" => $companyname
),
array(
"name" => "address",
"value" => $AddressLine1
),
...
)
);
PHP automatically builds an {} or [] depending on the contents.
So u just use the array() function to build the entire structure.
Something like this ...
$data = array();
array_push($data, array('name' => 'name', 'value' => $companyname));
array_push($data, array('name' => 'address', 'value' => $AddressLine1));
array_push($data, array('name' => 'address2', 'value' => $AddressLine2));
$output = array();
$output['properties'] = $data;
echo json_encode($output);

How to consolidate duplicate elements of this array in PHP?

I have an array like this:
$array = array(
0 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "memory"),
1 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "cpu"),
2 => array("ordernumber" => "1", "name" => "John", "product" => "desktop", "component" => "cpu"),
3 => array("ordernumber" => "2", "name" => "Pete", "product" => "monitor", "component" => "")
);
It contains data from different orders, but as you can see an order can contain multiple purchased products, and each product can contain different 'components'. There's alot of duplicate data in this array, so I would like to turn it into this:
$array = array(
0 => array(
"order" => array(
"ordernumber" => "1", "name" => "John"
),
"products" => array(
0 => array(
"name" => "laptop",
"components" => array("memory", "cpu")
),
1 => array(
"name" => "desktop",
"components" => array("cpu")
)
)
),
1 => array(
"order" => array(
"ordernumber" => "2", "name" => "Pete"
),
"products" => array(
0 => array(
"name" => "monitor",
"components" => array()
)
)
)
);
What would be a good way to do this?
Please use below code to make the solution what you want
<?php
$array = array(
0 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "memory"),
1 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "cpu"),
2 => array("ordernumber" => "1", "name" => "John", "product" => "desktop", "component" => "cpu"),
3 => array("ordernumber" => "2", "name" => "Pete", "product" => "monitor", "component" => "")
);
$final_array = [];
foreach($array as $k=>$v){
$final_array[$v['ordernumber']]['order']['ordernumber'] = $v['ordernumber'];
$final_array[$v['ordernumber']]['order']['name'] = $v['name'];
$final_array[$v['ordernumber']]['products'][$v['product']]['name'] = $v['product'];
$final_array[$v['ordernumber']]['products'][$v['product']]['components'][] = $v['component'];
}
// You can skip this foreach if there will not metter of KEY of an array in your code!
$final_array = array_values($final_array);
foreach($final_array as $k=>$v){
$final_array[$k]['products'] = array_values($final_array[$k]['products']);
}
echo "<pre>";
print_r($final_array);
?>
its should work!!

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']);

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