I've got a request to present the data in the following format as a JSON feed:
{
"id": "123",
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
{
"id": "456",
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}
However in my PHP code, I think I need to have a key itterator - but I end up with this format:
{
"0": {
"id": "123",
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
"1": {
"id": "456",
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}
}
Any ideas on how to build the first data set with out having the index iterator?
simple create an array of objects, no need for the key (notice the [ ] surrounding your list)
json.txt
[{
"id": "123",
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
{
"id": "456",
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}]
example.php
<?php
$data = json_decode(file_get_contents('./json.txt'));
?>
It can be built like this:
$arr = array(
array(
'id' => 123,
'info' => array(
'code' => 'ZGE',
'description' => 'test1',
'type' => 'AVL'
)
),
array(
'id' => 456,
'info' => array(
'code' => 'ZDN',
'description' => 'test2',
'type' => 'CLR'
)
)
);
echo json_encode($arr);
Outputs
[
{
"id": 123,
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL"
}
},
{
"id": 456,
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR"
}
}
]
the JSON format you've specified in the first example (ie the requested format) is not valid JSON.
A valid JSON string must evaluate to a single Javascript object; the example you've given evaluates to two Javascript objects, separated by a comma. In order to make it valid, you would need to either enclose the whole thing in square brackets, to turn it into a JS array or enclose it in curly braces, and give each of the two objects a key.
The PHP code you've written is doing the second of these two options. It is therefore generating valid JSON code, about as close to the original request as could be expected while still being valid.
It would help if you'd shown us the PHP code that you've used to do this; without that, I can't really give you advice on how to improve it, but if you want to switch to the square bracket notation, all you need is to put your PHP objects into an unkeyed array, and json_encode() should do it all for you; you shouldn't need to use a keyed array or an iterator for that.
The only reason json_encode should produce the output you're seeing is adding another named key to the array that you're passing to json_encode, by default it should work as you want:
$json = '[
{
"id": "123",
"recall_info": {
"code":"ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
{
"id": "123",
"recall_info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}
]';
$php = array(
(object) array(
'id' => '123',
'recall_info' => (object) array(
'code' => 'ZGE',
'description' => 'test1',
'type' => 'AVL',
'date' => '09/08/2012'
)
),
(object) array(
'id' => '123',
'recall_info' => (object) array(
'code' => 'ZGE',
'description' => 'test2',
'type' => 'CLR',
'date' => '16/02/2012'
)
)
);
var_dump(json_encode($php));
Related
I am trying to add a customer(Podio item) to my Podio app. This customer is being added programmatically from within a php application. There are several fields present on the customer: Name, Address, Email, Title, Phone Number, and an array of Tags. When a tag is added the color changes to highlight it.
In previous iterations I have been successful adding a different tag(newsletter_subscribed) using the ID of the tag value that I want highlighted. Now when I try to add another tag(hospital, clinic, or urgent_care) it is throwing a PodioBadRequestError. The error cited is that the ID being used is and invalid type(integer).
I got the values of the tag ID's by looking at the JSON returned when an existing customer created manually within my Podio customer application. When I look at the ID fields in the JSON they are most definitely integers, I have tried strings as well. Everything I try throws the 400 Bad Request on the ID that I am trying to add.
I cannot for the life of me figure out why it is throwing the error when I add the tag ID's.
Below is the way that the application is put together:
This is the code that builds and sends the request:
public function addToPodio()
{
$address = $this->Address . ", " .
$this->Address2 . ", " .
$this->City . ", " .
$this->State . " " .
$this->Zip;
$item = [
'fields' => [
'name' => $this->PrimaryContactFirstName,
'last-name' => $this->PrimaryContactLastName,
'email-address' => ['type' => 'work', 'value' => $this->PrimaryContactEmail],
'phone-number' => ['type' => 'work', 'value' => $this->PrimaryContactPhone],
'address' => $address,
'organization' => [$this->CompanyName],
'tags-2' => []
],
];
if ($this->Newsletter && defined('PODIO_NEWSLETTER_TAG_ID')){
$item['fields']['tags-2'][] = PODIO_NEWSLETTER_TAG_ID;
}
if($this->OrganizationType && defined('PODIO_ORGANIZATION_TYPE_ID')){
if($this->OrganizationType == "Clinic"){
$item['fields']['tags-2'][] = PODIO_ORGANIZATION_TYPE_CLINIC_TAG_ID;
}
else if($this->OrganizationType == "Hospital"){
$item['fields']['tags-2'][] = PODIO_ORGANIZATION_TYPE_HOSPITAL_TAG_ID;
}
try {
//This is where the request is being made
$customer = PodioItem::create(PODIO_CUSTOMER_APP_ID, $item);
$this->PodioId = $customer->item_id;
$this->write();
} catch (Exception $e) {
error_log('We encountered an error adding your item to Podio' . $e);
return 'An error occurred while updating Podio. Please try again. If the error...';
}
This is the PHP $item that is being passed to the request that gets sent to the Podio API:
Array
(
[fields] => Array
(
[name] => Joe
[last-name] => Test
[phone-number] => Array
(
[type] => work
[value] => 8675309
)
[address] => 123 Main Road, , East Test, NY 12345
[organization] => Array
(
[0] => Another Test
)
[tags-2] => Array
(
[0] => 16
[1] => 96
)
)
)
This is the config file with the all of the constants, secrets tokens and ID's needed to connect to the Podio API, authenticate and all of that stuff. Obfuscated Example below:
define('PODIO_CUSTOMER_APP_ID', 'xxxxx-obfuscated-xxxxx');
define('PODIO_CUSTOMER_APP_TOKEN', 'xxxxx-obfuscated-xxxxx');
define('PODIO_CLIENT_SECRET', 'xxxxx-obfuscated-xxxxx');
define('PODIO_CLIENT_ID', 'xxxxx-obfuscated-xxxxx');
define('PODIO_ORGANIZATION_TYPE_ID', 'xxxxx-obfuscated-xxxx');
define('PODIO_NEWSLETTER_TAG_ID', 'xxxxx-obfuscated-xxxxx');
define('PODIO_ORGANIZATION_TYPE_CLINIC_TAG_ID', 'xxxxx-obfuscated-xxxxx');
Podio::setup(PODIO_CLIENT_ID, PODIO_CLIENT_SECRET, [
'session_manager' => Injector::inst()->get(PodioSession::class),
'curl_options' => array(),
]);
Below is the JSON that I used to get the values of the ID's. I got this from a postman request to the API. The basic form of the request without all of the authentication present looked like:
podio.com/MY_PODIO_ACCOUNT_NAME/app/APPLICATION_ID/item/ITEM_ID
Please note: I removed many of the main fields like Address and Organization for brevity's sake, so it won't match completely the PHP request object above.
{
"id": 0000,
"item_id": 00000,
"revision": 0,
"app": null,
"app_item_id": 00000,
"app_item_id_formatted": "PODIO_Field_ID:00000",
"external_id": null,
"title": "TEST ITEM",
"fields": [
{
"id": 0000,
"field_id": 0000,
"type": "text",
"external_id": "name",
"label": "First Name",
"values": [
{
"value": "Joe"
}
],
"config": {
"settings": {
"format": "plain",
"size": "small"
},
"mapping": "contact_name",
"label": "First Name"
},
"humanized_value": "Joe"
},
{
"id": 0000,
"field_id": 0000,
"type": "text",
"external_id": "last-name",
"label": "Last Name",
"values": [
{
"value": "<p>Test<br /></p>"
}
],
"config": {
"settings": {
"format": "html",
"size": "large"
},
"mapping": null,
"label": "Last Name"
},
"humanized_value": "Test"
},
{
"id": 0000,
"field_id": 0000,
"type": "phone",
"external_id": "phone-number",
"label": "Phone Number",
"values": [
{
"type": "work",
"value": "867-5309"
}
],
"config": {
"settings": {
"call_link_scheme": "callto",
"possible_types": [
"mobile",
"work",
"home",
"main",
"work_fax",
"private_fax",
"other"
]
},
"mapping": "contact_phone",
"label": "Phone Number"
},
"humanized_value": "8675309"
},
{
"id": 11111,
"field_id": 11111,
"type": "category",
"external_id": "tags-2",
"label": "Tags",
"values": [
{
"value": {
"status": "active",
"text": "Clinic",
"id": 16,
"color": "DCEBD8"
}
},
{
"value": {
"status": "active",
"text": "Newlsetter_subscribed",
"id": 96,
"color": "DCEBD8"
}
}
],
"config": {
"settings": {
"multiple": true,
"options": [
{
"status": "active",
"text": "Mktng:test1/2020",
"id": 150,
"color": "DCEBD8"
},
{
"status": "active",
"text": "Mktng:Test2/2020",
"id": 3,
"color": "DCEBD8"
},
{
"status": "active",
"text": "SampleTest",
"id": 48,
"color": "DCEBD8"
},
{
"status": "deleted",
"text": "Test Center",
"id": 139,
"color": "DCEBD8"
},
{
"status": "deleted",
"text": "Sample Center",
"id": 99,
"color": "DCEBD8"
},
{
"status": "deleted",
"text": "Testing Center",
"id": 140,
"color": "DCEBD8"
}
],
"display": "inline"
},
"mapping": null,
"label": "Tags"
},
"humanized_value": "Clinic; Newsletter;"
}
this JSON continues for pages and pages, I only included the relevant fields for my question.
It looks like the error is being thrown because of the organization value, not the tags value.
For a category field, an array of integer indices is correct.
[tags-2] => [ 16, 96 ]
For an app field, you need to provide an array of integer item ID's.
[organization] => [ 12345 ]
But your code above is sending an array of strings:
[organization] => [ "Another Test" ]
That won't work.
I have two nested arrays with different length. I want to make length of second array as per first array, see below examples to get idea. Just remove all those items which don't exist in first array. Sometime second array has more values then first array, in this case my tree structure breaks.
These arrays are nested array so simple array_slice not working.
Here are the structure of array.
First Array
"1": {
"id": "1",
"username": "username",
"children": [
{
"id": "-1",
"username": "NULL",
"children": [
{
"id": "-1",
"username": "NULL",
"children": [
{
"id": "-1",
"username": "NULL",
"children": []
}
]
}
]
}
]
}
Second Array
"157": {
"id": "157",
"username": "test1",
"children": [
{
"id": "158",
"username": "test1",
"children": [
{
"id": "159",
"username": "test2",
"children": [
{
"id": "160",
"username": "test3",
"children": []
},
{
"id": "160",
"username": "KICK ME BECAUSE I M NOT EXIST IN FIRST ARRAY",
"children": []
}
]
}
]
},
{
"id": "160",
"username": "KICK ME BECAUSE I M NOT EXIST IN FIRST ARRAY",
"children": [
{
"id": "159",,
"username": "KICK ME BECAUSE I M NOT EXIST IN FIRST ARRAY",
"children": [
{
"id": "161",
"username": "KICK ME BECAUSE I M NOT EXIST IN FIRST ARRAY",
"children": []
}
]
}
]
}
]
}
Expected Output
"157": {
"id": "157",
"username": "test1",
"children": [
{
"id": "158",
"username": "test1",
"children": [
{
"id": "159",
"username": "test2",
"children": [
{
"id": "160",
"username": "test3",
"children": []
},
]
}
]
},
]
}
I am trying this method, but it is not working.
$firstCount = (array_map('count', $actualTree));
$secondCount = (array_map('count', $emptyTree));
$chunk = array_slice($actualTree, 0 , $second[$this->userId], true);
Use Case
The thing which I want to do is that remove those array childrens completely which are not exists in first array. I am building a binary tree upto three levels. First array already has a binary tree with empty values. The second array is data that is coming from the database, and I am simply replacing empty data with the actual data using array_replace. This is working good until second array has more values then first array. So to make it working I have to remove those extra elements.
Could anyone please help me to make there length same. Any help will be appreciated.
Thanks in advance.
A Stack Overflow miracle has occurred... I got a recursive snippet to work on the first pass! Usually it takes me a good hour or two to write something that works.
I don't know if I can make it any tighter/better OR if it will fail on any fringe cases, but:
it works for your sample input
it is midnight for me, I'm tired, and I have to work in the morning
Effectively, it synchronously & recursively iterates each array and stores each level of the entry array to the output array so long as the same level keys exists in the structure array.
Code: (Demo)
function truncateRecursive($structure, $entry) {
$output = [];
while (($structureKey = key($structure)) !== null && ($entryKey = key($entry)) !== null) {
$output[$entryKey] = !is_array($entry[$entryKey])
? $entry[$entryKey]
: truncateRecursive($structure[$structureKey], $entry[$entryKey]);
unset($structure[$structureKey], $entry[$entryKey]);
}
return $output;
}
var_export(truncateRecursive($structure, $entry));
Output:
array (
157 =>
array (
'id' => '157',
'username' => 'test1',
'children' =>
array (
0 =>
array (
'id' => '158',
'username' => 'test1',
'children' =>
array (
0 =>
array (
'id' => '159',
'username' => 'test2',
'children' =>
array (
0 =>
array (
'id' => '160',
'username' => 'test3',
'children' =>
array (
),
),
),
),
),
),
),
),
)
This question already has answers here:
Creating a jSON object using php loop
(2 answers)
Create a Json array in a for loop - php
(2 answers)
Closed 1 year ago.
How to add commas to a json print?
$result = curl($url);
$result = json_decode($result , true);
$resultdata = $result ['data'];
foreach($resultdata as $data){
$print= array(
"id" => $data['id'],
"username" => $data['username'],
"text" => $data['text']
);
print json_encode($print);
}
this is the response from my code
{
"id": "17996292388215089",
"username": "hanikfadhilah",
"text": "Loh kapan ini huuu pengen"
}
{
"id": "17877856039348099",
"username": "titan_kdk",
"text": "Mntb"
}
{
"id": "17860767967398064",
"username": "explorecentraljava",
"text": "Terbaik fotonya lur"
}
I want to have a comma for each json result
{
"id": "17996292388215089",
"username": "hanikfadhilah",
"text": "Loh kapan ini huuu pengen"
},{
"id": "17877856039348099",
"username": "titan_kdk",
"text": "Mntb"
},{
"id": "17860767967398064",
"username": "explorecentraljava",
"text": "Terbaik fotonya lur"
}
What you actually need to do is produce an array of results, which you can do by pushing values into an array in the loop, and then json_encode the array after the loop:
$print = array();
foreach($resultdata as $data){
$print[]= array(
"id" => $data['id'],
"username" => $data['username'],
"text" => $data['text']
);
}
print json_encode($print);
I don't get the point of having ',' but I'm guessing you want a valid json output. If so I guess that your result data is an array:
<?php
$result = [ 'data' => [
[
"id" => "17996292388215089",
"username" => "hanikfadhilah",
"text" => "Loh kapan ini huuu pengen"
],
[
"id" => "17877856039348099",
"username" => "titan_kdk",
"text" => "Mntb"
],
[
"id" => "17860767967398064",
"username" => "explorecentraljava",
"text" => "Terbaik fotonya lur"
]
]
];
so all what you need to do in order to get it as a valid json is:
print json_encode($result['data'], JSON_PRETTY_PRINT);
that produces output:
[
{
"id": "17996292388215089",
"username": "hanikfadhilah",
"text": "Loh kapan ini huuu pengen"
},
{
"id": "17877856039348099",
"username": "titan_kdk",
"text": "Mntb"
},
{
"id": "17860767967398064",
"username": "explorecentraljava",
"text": "Terbaik fotonya lur"
}
]
no need for any foreach loop.
json_encode()
We are working with an API that brings back JSON in this format:
[
{
"Id": "d7526186-361c-e611-80da-00155df41a0a",
"LogicalName": "contact",
"Attributes": [
{
"Key": "customertypecode",
"Value": {
"Value": 1
}
},
{
"Key": "merged",
"Value": false
},
{
"Key": "territorycode",
"Value": {
"Value": 1
}
}
],
"EntityState": null,
"FormattedValues": [
{
"Key": "customertypecode",
"Value": "Default Value"
},
{
"Key": "address2_addresstypecode",
"Value": "Default Value"
},
{
"Key": "merged",
"Value": "No"
},
{
I am currently using foreach to organise this into a new, cleaner array - but the code base is getting rather large.
What would be the cleanest way of getting specific values based on specifying a key name?
Thanks so much for your help.
First using json_decode to convert to an array, then you can access it in any way you would a normal multi dimensional array... e.g.
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo"
)
)
);
var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);
from http://php.net/manual/en/language.types.array.php
Forgive my terminology im a newbie in in web dev.
To visualize my question, see below.
This is how RESTLER displays json:
[
{
"id": 1,
"name": "Daniel Craig",
"email": "dc#gmail.com"
},
{
"id": 2,
"name": "Tom Cruise",
"email": "tc#gmail.com"
}
]
This is how i would want RESTLER to display json results:
{"actors":[
{
"id": 1,
"name": "Daniel Craig",
"email": "dc#gmail.com"
},
{
"id": 2,
"name": "Tom Cruise",
"email": "tc#gmail.com"
}
]}
Just wrap your result with another array. if we assume that $result returns the first result above, do the following
$result = array(
array(
"id" => 1,
"name" => "Daniel Craig",
"email" => "dc#gmail.com"
),
array(
"id" => 2,
"name" => "Tom Cruise",
"email" => "tc#gmail.com"
)
);
return array('actors'=>$result);