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

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! :)

Related

Display data from two arrays having one common point

I have two arrays.
The first one is about exchange-rate and the display in my console is like this :
{
"exchange_rate": [
{
"id": "978",
"start_dateTime": "2021-08-01 07:35:02",
"target_value": "1.00000",
"currency_value_euro": "0.84097",
"currency_value_dollar_us": "1.00000",
"id_currency": "1",
"currency": "Dollar am\u00e9ricain",
"currency_symbol": "$US"
},
{
"id": "980",
"start_dateTime": "2021-08-01 07:35:02",
"target_value": "1.00000",
"currency_value_euro": "1.17454",
"currency_value_dollar_us": "0.71600",
"id_currency": "2",
"currency": "Livre sterling",
"currency_symbol": "\u00a3"
}
]
}
These data came from the database and I can display it by choosing particular dates with jQuery.
The second array contains only id_currency which in my console is like this : Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5
On my website, I want to be able to display specific exchange rate by specific currency and dates.
And here my problem appears, I can't find the way to loop on the first array, and loop again inside, on the second array and compare both like if first array has id_currency 1 and second array has id_currency 1 then display the complete line from first array.
I've tried several things but nothing works, at last i've tried this :
foreach ($res as $row){
$idBDD = $row['id_currency'];
$symbolBDD = $row['currency_symbol'];
echo $idBDD;
echo $symbolBDD;
//var_dump($row);
/*foreach ($arr as $line){
$idCheckbox = $line;
echo $idCheckbox;
}
if ($idBDD == $idCheckbox){
echo 'fine';
}
*/
}
I'll be grateful for your help
You need to access the array with $res["exchange_rate"] and loop through it then.
<?php
$res = [
"exchange_rate" => [
[
"id" => "978",
"start_dateTime" => "2021-08-01 07:35:02",
"target_value" => "1.00000",
"currency_value_euro" => "0.84097",
"currency_value_dollar_us" => "1.00000",
"id_currency" => "1",
"currency" => "Dollar américain",
"currency_symbol" => "\$US"
],
[
"id" => "980",
"start_dateTime" => "2021-08-01 07:35:02",
"target_value" => "1.00000",
"currency_value_euro" => "1.17454",
"currency_value_dollar_us" => "0.71600",
"id_currency" => "2",
"currency" => "Livre sterling",
"currency_symbol" => "£"
]
]
];
$output = null;
foreach ($res["exchange_rate"] as $row) {
if (!isset($output)) {
$output = $row;
}
$output = array_intersect_assoc($output, $row);
}
var_dump($output);
I think you could do it like this, of course if you're inside the loop, you won't need to put indices.
read more array_diff()
https://www.php.net/manual/pt_BR/function.array-diff.php
$array = [
"exchange_rate" => [
[
"id" => "978",
"start_dateTime" => "2021-08-01 07:35:02",
"target_value"=> "1.00000",
"currency_value_euro"=> "0.84097",
"currency_value_dollar_us"=> "1.00000",
"id_currency"=> "1",
"currency"=> "Dollar am\u00e9ricain",
"currency_symbol" => "US"
],[
"id"=> "980",
"start_dateTime"=> "2021-08-01 07=> 35=> 02",
"target_value"=> "1.00000",
"currency_value_euro"=> "1.17454",
"currency_value_dollar_us"=> "0.71600",
"id_currency"=> "2",
"currency"=> "Livre sterling",
"currency_symbol"=> "\u00a3"
]
]
];
$array1 = $array['exchange_rate'][0];
$array2 = $array['exchange_rate'][1];
$result = array_diff( $array1, $array2);
var_dump($result);

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

foreach use value from object twice

I recieve json objects like the following over an rest-service
[
{
"pos_time": "04.09.2018 09:57:02",
"receivetime": "04.09.2018 09:57:18",
"latitude": 47554898,
"longitude": 13173448,
"speed": 8,
"course": 359,
"country": "AT"
},
{
"pos_time": "04.09.2018 09:58:02",
"receivetime": "04.09.2018 09:58:31",
"latitude": 47835502,
"longitude": 13653503,
"speed": 7,
"course": 174,
"country": "AT"
},
]
form this json I want to create a geojson "linestring".
The "linestring" is not the problem. the problem is, that I have to use both coordinates of each object to create the "linestring"
and I have no idea how to loop through the objects and use the coordinates from the second object and first object to create the "linestring"
the result should look like this:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"pos_time": "04.09.2018 09:56:22",
"receivetime": "04.09.2018 09:57:18",
"course": 177,
"speed": 2,
"country": "AT",
"error": null
},
"geometry": {
"type": "LineString",
"coordinates": [
[
13.173448, // object 1
47.554898 // object 1
],
[
13.653503, // object 2
47.835502 // object 2
]
]
}
}
]
}
and the code for the moment looks like this:
// create geojson
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
///////
foreach ($tomtom_request_array as $key => $value) {
if (empty($value['longitude']) || empty($value['latitude']))
{
$longitude = "13.07202";
$latitude = "47.889486";
$error = "Missing or incorrect GPS data";
}
else
{
$latitude = $value['longitude']; // object 1
$longitude = $value['latitude']; // object 1
$latitude_previous = $value['longitude']; // object 2
$longitude_previous = $value['latitude']; // object 2
$error = NULL;
}
if (empty($value['speed']))
{
$speed = "0";
}
else
{
$speed = $value['speed'];
}
if (empty($value['course']))
{
$course = "0";
}
else
{
$course = $value['course'];
}
$feature = array(
'type' => 'Feature',
'properties' => array(
'pos_time' => $value['pos_time'],
'receivetime' => $value['receivetime'],
'course' => $course,
'speed' => $speed,
'country' => $value['country'],
'error' => $error
),
'geometry' => array(
'type' => 'LineString',
'coordinates' => array(
array(($latitude * 0.000001), ($longitude* 0.000001)),
array(($latitude_previous * 0.000001), ($longitude_previous* 0.000001))
),
),
);
array_push($geojson['features'], $feature);
}
$this->response($geojson, $response_status);
}
thanks in advance!
if your Json response is really as you said so it is elementary my dear.You just need to use respective index to retrieve the desired data:
example:
given your JSON response you can proceed like this:
$tomtom_request_array=json_decode('[
{
"pos_time": "04.09.2018 09:57:02",
"receivetime": "04.09.2018 09:57:18",
"latitude": 47554898,
"longitude": 13173448,
"speed": 8,
"course": 359,
"country": "AT"
},
{
"pos_time": "04.09.2018 09:58:02",
"receivetime": "04.09.2018 09:58:31",
"latitude": 47835502,
"longitude": 13653503,
"speed": 7,
"course": 174,
"country": "AT"
}
]',true) ;
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
///////
foreach ($tomtom_request_array as $key => $value) {
if (empty($value['longitude']) || empty($value['latitude']))
{
$longitude = "13.07202";
$latitude = "47.889486";
$error = "Missing or incorrect GPS data";
}
else
{
$latitude = $tomtom_request_array[0]['longitude']; // object 1
$longitude = $tomtom_request_array[0]['latitude']; // object 1
$latitude_previous =$tomtom_request_array[1]['longitude']; // object 2
$longitude_previous =$tomtom_request_array[1]['latitude']; // object 2
$error = NULL;
}
if (empty($value['speed']))
{
$speed = "0";
}
else
{
$speed = $value['speed'];
}
if (empty($value['course']))
{
$course = "0";
}
else
{
$course = $value['course'];
}
$feature = array(
'type' => 'Feature',
'properties' => array(
'pos_time' => $value['pos_time'],
'receivetime' => $value['receivetime'],
'course' => $course,
'speed' => $speed,
'country' => $value['country'],
'error' => $error
),
'geometry' => array(
'type' => 'LineString',
'coordinates' => array(
array(($latitude * 0.000001), ($longitude* 0.000001)),
array(($latitude_previous * 0.000001), ($longitude_previous* 0.000001))
),
),
);
array_push($geojson['features'], $feature);
}
At this step $geojson contains :
print_r($geojson);
Array
(
[type] => FeatureCollection
[features] => Array
(
[0] => Array
(
[type] => Feature
[properties] => Array
(
[pos_time] => 04.09.2018 09:57:02
[receivetime] => 04.09.2018 09:57:18
[course] => 359
[speed] => 8
[country] => AT
[error] =>
)
[geometry] => Array
(
[type] => LineString
[coordinates] => Array
(
[0] => Array
(
[0] => 13.173448
[1] => 47.554898
)
[1] => Array
(
[0] => 13.653503
[1] => 47.835502
)
)
)
)
[1] => Array
(
[type] => Feature
[properties] => Array
(
[pos_time] => 04.09.2018 09:58:02
[receivetime] => 04.09.2018 09:58:31
[course] => 174
[speed] => 7
[country] => AT
[error] =>
)
[geometry] => Array
(
[type] => LineString
[coordinates] => Array
(
[0] => Array
(
[0] => 13.173448
[1] => 47.554898
)
[1] => Array
(
[0] => 13.653503
[1] => 47.835502
)
)
)
)
)
)

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";
});

Converting php object to json

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.

Categories