Converting php object to json - php

I've a php object that I want to convert to the following json format.
All the data values are object via a php object in the format:
Array ( [0] => stdClass Object ( [id] => 2
[s1] => 1485
[name] => 1485
[credit] => ''
[caption] => ''
)
)
I'm trying to group the credit, caption, etc. under child. Also, I'm unable to get the [ after date in the json format.
{
"mydata":
{
"name":Name,
"type":"default",
"date": [
{
"s1":"1485",
"name":"1485",
"child":
{
"credit":"",
"caption":""
}
}]
}
}
Currently, my code looks like:
foreach ($hits as $hit) {
$data->mydata->date->s1 = $hit->s1;
$data->mydata->date->name = $hit->name;
$data->mydata->date->credit = $hit->credit;
$data->mydata->date->caption = $hit->caption;
}
$a = json_encode($data);

set $date->mydata->date to an array and you will get the []
And why not making more nested structures?

The JSON format you're looking at shows that date is an array (the brackets are array notation in javascript), so:
<?php
$var = array(
'mydata' => array(
'name' => 'Name',
'type' => 'default',
'date' => array(
array(
's1' => 1485,
'name' => '1485',
'child' => array(
'credit' => '',
'caption' => '',
),
),
),
),
);
print json_encode($var);
prints out:
{
"mydata": {
"name": "Name",
"type": "default",
"date": [
{
"s1": 1485,
"name": "1485",
"child": {
"credit": "",
"caption": ""
}
}
]
}
}
No need to try and add stdClass instances or anything like that in PHP. Just build out a nice clean array and JSON encode will convert to object properties and arrays where necessary.

Related

Difficulty to understand PHP POST to REST API - mixed array and objects

I'm trying to POST data to a REST API.
On Postman I can POST with success, the JSON body is:
{
"version": 0,
"roles": {
"customer": {
}
},
"person": {
"firstName": "Inge",
"lastName": "Musterfrau"
},
"emailAddresses" :{
"private" : [
"email#domain.com"
]
},
"addresses": {
"billing": [
{
"supplement": null,
"street": "aaa",
"zip": "12345",
"city": "Berlin",
"countryCode": "DE"
}
]
}
}
My problem is on addresses billing. I don't know how to create the object/array correctly so the API accept it.
I'm build the parameters on PHO like bellow:
$billingAddr = array(
"supplement" => $billingAddress["streetDetails"],
"street" => $billingAddress["street"],
"zip" => $billingAddress["zipCode"],
"city" => $billingAddress["city"],
"countryCode" => $billingAddress["country"],
);
$params = [
"version" => 0,
"roles" => $roles,
"person" => $person,
"emailAddresses" => $emailAddresses,
"addresses" => [
"billing" => $billingAddr
]
];
I get an error: "missing_entity - addresses - validation_failure".
I believe my issue is creating the mixed Object addresses, array billing.
So, going strictly by the PHP example, doing a json_encode'd output of that shows that the structure is not quite the same at the addresses.
Note that I do not have the data for most of the rest of the json info from the PHP example, so the output examples below are strictly focused on the addresses section.
Before JSON change:
echo json_encode($params, JSON_PRETTY_PRINT);
{
"version": 0,
"roles": null,
"person": null,
"emailAddresses": null,
"addresses": {
"billing": {
"supplement": null,
"street": null,
"zip": null,
"city": null,
"countryCode": null
}
}
}
... in that, note that the billing does not have the [] characters like what is sent using postman.
No worries though, it's an easy fix. The addresses part should be changed to get an array of billing addresses, like so:
"addresses" => [
"billing" => [$billingAddr]
]
Then running a recheck with that change applied shows:
After JSON change:
echo json_encode($params, JSON_PRETTY_PRINT);
{
"version": 0,
"roles": null,
"person": null,
"emailAddresses": null,
"addresses": {
"billing": [
{
"supplement": null,
"street": null,
"zip": null,
"city": null,
"countryCode": null
}
]
}
}
That should help to achieve the expected format.
Here's the fiddle example in case you might need another PHP version to check. The fiddle default is 8.0.1
Object properties and associative arrays are easy to access/declare directly; however, when you need to push data into indexed subarrays, you can to use [] syntax or array_push().
If you want to build a bit more maintainability in this code, you can build the variable-length subarrays as individual variables and then feed them into the master array just before json_encoding.
$version = 0;
$roles = ['customer' => []];
$person = [
'firstName' => 'Inge',
'lastName' => 'Musterfrau'
];
$emailAddresses = [
'private' => [
'email#domain.com',
]
];
$billingAddresses[] = [
'supplement' => $billingAddress["streetDetails"],
'street' => $billingAddress["street"],
'zip' => $billingAddress["zipCode"],
'city' => $billingAddress["city"],
'countryCode' => $billingAddress["country"]
];
// use $billingAddresses[] again to push another subarray into $billing
$data = [
'version' => $version,
'roles' => $roles,
'person' => $person,
'emailAddresses' => $emailAddresses,
'addresses' => [
'billing' => $billingAddresses
]
]
This will create your array/json :
$arr['version'] = "0";
$arr['roles']['customer'] = [];
$arr['person']['firstName'] = "Inge";
$arr['person']['lastName'] = "Musterfrau";
$arr['emailAddresses']['private'][] = "email#domain.com";
$arr['addresses']['billing'][0]['supplement'] = "";
$arr['addresses']['billing'][0]['street'] = "aaa";
$arr['addresses']['billing'][0]['zip'] = "12345";
$arr['addresses']['billing'][0]['city'] = "Berlin";
$arr['addresses']['billing'][0]['countryCode'] = "DE";
$newJson = json_encode($arr);
Afterwards you json_encode it and voila the perfect json and very simple!
The best and easiest way to look at a json (to my opinion at least:) is as an array! (no shame in using the browser and echo "<pre>" here!) - We'll build an identical array and json it up back!
Once we see the json as an array we build the same in a very simple way here is the whole code example with step by step:
<?php
/*Our original json */
$json = '{
"version": 0,
"roles": {
"customer": {
}
},
"person": {
"firstName": "Inge",
"lastName": "Musterfrau"
},
"emailAddresses" :{
"private" : [
"email#domain.com"
]
},
"addresses": {
"billing": [
{
"supplement": null,
"street": "aaa",
"zip": "12345",
"city": "Berlin",
"countryCode": "DE"
}
]
}
}';
$array = json_decode($json,true);
echo '<pre>';
/* original array */
echo "original array: ";
print_r($array);
echo '<pre>';
/* now lets create the same array with less fuss?! */
$arr['version'] = "0";
$arr['roles']['customer'] = [];
$arr['person']['firstName'] = "Inge";
$arr['person']['lastName'] = "Musterfrau";
$arr['emailAddresses']['private'][] = "email#domain.com";
$arr['addresses']['billing'][0]['supplement'] = "";
$arr['addresses']['billing'][0]['street'] = "aaa";
$arr['addresses']['billing'][0]['zip'] = "12345";
$arr['addresses']['billing'][0]['city'] = "Berlin";
$arr['addresses']['billing'][0]['countryCode'] = "DE";
/* the new array: */
echo "our newly created array: ";
echo '<pre>';
print_r($arr);
echo '<pre>';
/* back to json */
echo "new Json: ";
echo '<pre>';
$newJson = json_encode($arr);
print_r($newJson);
This will return:
original array: Array
(
[version] => 0
[roles] => Array
(
[customer] => Array
(
)
)
[person] => Array
(
[firstName] => Inge
[lastName] => Musterfrau
)
[emailAddresses] => Array
(
[private] => Array
(
[0] => email#domain.com
)
)
[addresses] => Array
(
[billing] => Array
(
[0] => Array
(
[supplement] =>
[street] => aaa
[zip] => 12345
[city] => Berlin
[countryCode] => DE
)
)
)
)
our newly created array:
Array
(
[version] => 0
[roles] => Array
(
[customer] => Array
(
)
)
[person] => Array
(
[firstName] => Inge
[lastName] => Musterfrau
)
[emailAddresses] => Array
(
[private] => Array
(
[0] => email#domain.com
)
)
[addresses] => Array
(
[billing] => Array
(
[0] => Array
(
[supplement] =>
[street] => aaa
[zip] => 12345
[city] => Berlin
[countryCode] => DE
)
)
)
)
new Json:
{"version":"0","roles":{"customer":[]},"person":{"firstName":"Inge","lastName":"Musterfrau"},"emailAddresses":{"private":["email#domain.com"]},"addresses":{"billing":[{"supplement":"","street":"aaa","zip":"12345","city":"Berlin","countryCode":"DE"}]}}
Building arrays can be very simple this way - almost feels linear! :)

Add another item to array associative in php

im having some issues adding a new item to an associative array,
This is how i'm creating my structure:
$cpdata[$count] = array(
'value' => $value->value,
'images' => array(
'color' => $value->color,
'image' => $value->image,
),
);
and this is how it looks like when i output like a json:
{
"value": "BOX",
"images": {
"color": "white",
"image": "white.png"
}
}
But i would like to add more items to images somthing like this:
{
"value": "BOX",
"images": [
{
"color": "white",
"image": "white.png"
},
{
"color": "black",
"image": "black.png"
},
{
"color": "gray",
"image": "gray.png"
}
]
}
I've tried with array_push and array_merge but i cant get it
i've tried array_push($cpdata['images'][$count]['images'], 'color'=>'red', image' => 'red.png')
Could you please help me?
Regards
Mario
In context of PHP, what you have there is a JSON variable. If that is coming to you as a string you'll have to decode it first using json_decode($string);
Then you can set up an object, populate it with the image variables and write it back to the $json object as an array, like:
<?php
// example code
$json = <<<EOT
{
"value": "BOX",
"images": {
"color": "white",
"image": "white.png"
}
}
EOT;
$json = json_decode($json);
$i = new stdClass;
$i->color = $json->images->color;
$i->image = $json->images->image;
$json->images = array($i);
After that you can push to it like
$newimage = new stdClass;
$newimage->color = "foo";
$newimage->image = "bar";
$json->images[] = $newimage;
output
print_r($json);
stdClass Object
(
[value] => BOX
[images] => Array
(
[0] => stdClass Object
(
[color] => white
[image] => white.png
)
[1] => stdClass Object
(
[color] => foo
[image] => bar
)
)
)
example https://www.tehplayground.com/oBS1SN1ze1DsVmIn
Before converting into json
$cpdata[$count] = array(
'value' => $value->value,
'images' => array(
'color' => $value->color,
'image' => $value->image,
),
);
// Cpdata array has $count which has `images` as an array and we want to push another element(array) into images array
array_push($cpdata[$count]['images'], ['color'=>'red', 'image' => 'red.png']);

PHP create value variable for json_encode function

I'm using a JSON API; I want to create a variable with values and then convert it to a JSON string via json_encode. The (working) JSON string is this:
$data = '
{
"function":"setArticleImages",
"paras":{
"user":"'.$user.'",
"pass":"'.$pass.'",
"product_model":"'.$productsModel.'",
"images":{
"products_id":'.$products_id.',
"image_name":"'.$imageName.'",
"image":"'.$image.'",
"products_images":[{
"products_id":'.$products_id.',
"image_name":"'.$imageName2.'",
"image":"'.$image2.'"
} ]
}
}}
';
I was now trying to write it like this and use json_encode:
$data = array(
"function" => "setArticleImages",
"paras" => array(
"user" => $user,
"pass" => $pass,
"product_model" => $productsModel,
"images" => array(
"products_id" => $products_id,
"image_name" => $imageName,
"image" => $image,
"products_images" => array(
"products_id" => $products_id,
"image_name" => $imageName2,
"image" => $image2,
),
)
)
);
$data = json_encode($data);
Unfortunately it does not work. The problems seems to be at '"products_images" => array('. I don't know how to handle the '[' of the '"products_images":[{' part.
Anyone an idea how to write it in the second code snippet?
You just need to add an extra level of array to the products_images element, so that you get a numerically indexed array of associative arrays, giving you the array of objects form you want:
$data = array(
"function" => "setArticleImages",
"paras" => array(
"user" => $user,
"pass" => $pass,
"product_model" => $productsModel,
"images" => array(
"products_id" => $products_id,
"image_name" => $imageName,
"image" => $image,
"products_images" => array(
array(
"products_id" => $products_id,
"image_name" => $imageName2,
"image" => $image2,
)
),
)
)
);
Demo on 3v4l.org
The "{ }" in th JSON notation is a PHP array with alphanumerical key.
So :
$array = ["foo" => [1,2,3], "bar" => [4,5,6]
will be converted in a JSON string :
{ foo : [1,2,3], bar: [4,5,6]}
So if you are looking to a JSON that looks like this
[{ foo : [1,2,3], bar: [4,5,6]}]
You will have to do an array with numeric keys that contains your alphanumerical array :
$array = [["foo" => [1,2,3], "bar" => [4,5,6]]];
// same as
$array = [ 0 => ["foo" => [1,2,3], "bar" => [4,5,6]]];

Use array_filter on multi dimensional array

I'm trying to filter an array that looks like this
$array = array(
"id" => "SomeID",
"name" => "SomeName",
"Members" => array(
"otherID" => "theValueIamLookingFor",
"someOtherKey" => "something"
)
);
Now, I'm filtering for data sets, where "otherID" is a certain value. I know I could use array_filter to filter for "id", but I can't for the life of me figure out how to filter for a value in an array inside an array.
Adding some of the data as provided by the WebAPI (I run that through json_decode to create an associative array before all this filtering business)
[
{
"id": "b679d716-7cfa-42c4-9394-3abcdged",
"name": "someName",
"actualCloseDate": "9999-12-31T00:00:00+01:00",
"members": [
{
"otherID": "31f27f9e-abcd-1234-aslkdhkj2j4",
"name": "someCompany"
}
],
"competitor": null,
},
{
"id": "c315471f-45678-4as45-457-asli74hjkl",
"name": "someName",
"actualCloseDate": "9999-12-31T00:00:00+01:00",
"members": [
{
"otherID": "askgfas-agskf-as",
"name": "someName"
}
],
"competitor": null,
},
]
You can do something like:
$arr = array(
array(
"id" => "SomeID",
"name" => "SomeName",
"Members" => array (
"otherID" => "ThisIsNottheValueIamLookingFor",
"someOtherKey" => "something"
)
),
array(
"id" => "SomeID",
"name" => "SomeName",
"Members" => array (
"otherID" => "theValueIamLookingFor",
"someOtherKey" => "something"
)
),
array(
"id" => "SomeID",
"name" => "SomeName",
"Members" => array (
"otherID" => "ThisIsNottheValueIamLookingForEither",
"someOtherKey" => "something"
)
),
);
$result = array_filter($arr, function( $v ){
return $v["Members"]["otherID"] == "theValueIamLookingFor";
});
This will result to:
Array
(
[1] => Array
(
[id] => SomeID
[name] => SomeName
[Members] => Array
(
[otherID] => theValueIamLookingFor
[someOtherKey] => something
)
)
)
Here is the doc for more info: http://php.net/manual/en/function.array-filter.php
UPDATE
On you Updated array, the structure of array is different. You have to use $v["members"][0]["otherID"] to get the otherID
Please try the code below:
$result = array_filter($arr, function( $v ){
return $v["members"][0]["otherID"] == "theValueIamLookingFor";
});

In PHP, how do you output JSON iterating first on a child array, then on parent?

I have tried for several weeks to get this to work, and have given in. I need to display the following array in JSON.
As you can see, [coloroptions] is itself a JSON array, making this a multidimensional array. The trick is (I think) to iterate over the array, first on the child [coloroptions], then on the parent. I am probably way off base, though. Has anyone done anything like this?
Thank you, in advance!
SAMPLE DATA from print_r()
Array
(
[0] => Array
(
[id] => 1
[automobile] => 'Mustang'
[coloroptions] => [{"color":"red"},{"color":"blue"},{"color":"green"}]
)
[1] => Array
(
[id] => 2
[automobile] => 'Camero'
[coloroptions] => [{"color":"red"},{"color":"orange"}]
)
)
JSON output
[
{
"id": 1,
"automobile": "Mustang",
"color": "red"
},
{
"id": 1,
"automobile": "Mustang",
"color": "blue"
},
{
"id": 1,
"automobile": "Mustang",
"color": "green"
},
{
"id": 2,
"automobile": "Camero",
"color": "red"
},
{
"id": 2,
"automobile": "Camero",
"color": "orange"
},
]
I think you're close! My approach would be to use json_decode on the colours, and iterate over them like a normal PHP array.
// First, start by looping through each 'parent':
foreach($array as $key => $value)
{
// Decode the json color array into a normal php array
$colorarray = json_decode($value['coloroptions'], true);
/* Loop through each of the colours.
(Note that they'll be a few layers deep.
Do a print_r($colorarray) to see it's structure) */
foreach($colorarray as $color)
{
// And build your output array:
$output[] = array(
"id" => $value['id'],
"automobile" => $value['automobile'],
"color" => $color['color']
);
}
}
To check the final PHP array you can print_r($output). To convert $output into a json array, use json_encode
json_encode($output);
Well , you need to json_decode the coloroptions and output the assembled array with colors inside it to the result array.
$a = array(
array(
'id' => 1,
'automobile' => 'Mustang',
'coloroptions' => '[{"color":"red"},{"color":"blue"},{"color":"green"}]'
),
array(
'id' => 2,
'automobile' => 'Camero',
'coloroptions' => '[{"color":"red"},{"color":"orange"}]'
),
);
$result = array();
foreach($a as $key => $value) {
$coloroptions = json_decode($value['coloroptions']);
foreach($coloroptions as $color){
$result[] = array(
'id' => $value['id'],
'automobile' => $value['automobile'],
'color' => $color->color,
);
}
}
print_r(json_encode($result));
see the example here

Categories