Passing array to an API - php

i am trying to pass an array to an API, the API takes array in following format when i run it in POSTMAN (raw form),
{
"records": [
{
"content": "50.150.50.55",
"type": "A",
"name": "test.mauqe.com",
"prio": null,
"ttl": 3600
}
]
}
while am trying to pass the array in my code in this format,
$data = array(
"content" => "50.150.50.55",
"type" => "A",
"name" => "gulpanra.mauqe.com",
"prio" => "null",
"ttl" => "3600"
);
i don't understand, whats the problem. response said error (Data sending format error). plz help

The API expects an array of maps. The following is an array of maps.
[
{
"content": "50.150.50.55",
"type": "A",
"name": "test.mauqe.com",
"prio": null,
"ttl": 3600
},
{},
{},
...
]
What you are passing is not the same. You're passing in a single map
{
"content" => "50.150.50.55",
"type" => "A",
"name" => "gulpanra.mauqe.com",
"prio" => "null",
"ttl" => "3600"
}
Try amending $data to:
$data = array();
array_push($data['records'], array(
"content" => "50.150.50.55",
"type" => "A",
"name" => "gulpanra.mauqe.com",
"prio" => "null",
"ttl" => "3600"
));

<?php
$data = array('records' => array());
$data['records'][] = array(
"content" => "50.150.50.55",
"type" => "A",
"name" => "gulpanra.mauqe.com",
"prio" => null,
"ttl" => 3600
);
$json_output = json_encode( $data );
echo $json_output;
?>
This will give the following as output:
{"records":[{"content":"50.150.50.55","type":"A","name":"gulpanra.mauqe.com","prio":null,"ttl":3600}]}

Use json_encode to convert your array in json format and then pass it to the api.
The Api you are using is expecting data in json format.
$data = json_encode($data);

You will need to convert array into json format in order to pass it to the api. use json_encode(). Use the code below
$array = array( "content" => "50.150.50.55", "type" => "A", "name" => "gulpanra.mauqe.com", "prio" => "null", "ttl" => "3600" );
$data = json_encode($data); // Pass this to API
Hope this helps you

you have to make array outside for example
you are using this type of array to encode
$data['records'] = array(
'content' => '50.150.50.55',
and so on
);
change this array to this
$data = array(
'content' => '50.150.50.55',
and so on
);
this will help

Related

Laravel unit testing json response

I have the following test in my app. However the response isn't passing the test, and I can't see why...
public function test_get()
{
$user = $this->signInAsUser();
$product = factory('App\Models\Product')->create();
factory('App\Models\Stock')->create([
'product_id' => $product->id,
'qty' => $qty = rand(1, 100),
]);
$this->json('GET', '/api/stock', , ['Accept' => 'application/json'])
->assertStatus(200)
->assertJson([
'data' => [
'product_id' => "$product->id",
'stock' => "$qty"
]
]);
}
This produces the following from PHPUnit:
Unable to find JSON:
[{
"data": {
"product_id": "1",
"stock": "55"
}
}]
within response JSON:
[{
"data": [
{
"product_id": "1",
"stock": "55"
}
]
}].
Failed asserting that an array has the subset Array &0 (
'data' => Array &1 (
'product_id' => '1'
'stock' => '55'
)
).
The assertion is failing the test and I can't see why as the JSON looks the same to me...
You're asserting your JSON response is a single object, whereas it is an array of objects. Try using assertJsonFragment rather than assertJson.

PHP efficient way to combine two associative arrays into one multidimensional associative array

This is the first problem:
I have two Associative Arrays, one containing sales persons and one containing clients.
$salesPersons = array(
array(
"id" => "1",
"name" => "Mr Smith",
"email" => "mrsmith#email.com",
"clients" => array()
),
array(
"id" => "2",
"name" => "James Bond",
"email" => "jamesbond#email.com",
"clients" => array()
)
);
$clients = array(
array(
"id" => "1",
"name" => "Lucifer Enterprises",
"salesPersonId" => "1"
),
array(
"id" => "2",
"name" => "Charlies Chocolate Factory",
"salesPersonId" => "1"
),
array(
"id" => "3",
"name" => "Geckos Investments",
"salesPersonId" => "2"
),
);
I want to map $salesPersons['id'] to clients['salesPersonId'] by ID and return a multidimensional associative array like this:
$result_i_want = array(
array(
"id" => "1",
"name" => "Mr Smith",
"email" => "mrsmith#email.com",
"clients" => array(
array(
"id" => "1",
"name" => "Lucifer Enterprises",
),
array(
"id" => "2",
"name" => "Charlies Chocolate Factory",
),
)
),
array(
"id" => "2",
"name" => "James Bond",
"email" => "jamesbond#email.com",
"clients" => array(
array(
"id" => "3",
"name" => "Geckos Investments",
),
)
)
);
My solution to the first problem
I have solved it using nested foreach-loops and array_push
$result = array();
foreach ($clients as $c_record) {
foreach ($salesPersons as $s_record) {
if ($c_record['salesPersonId'] == $s_record['id']) {
array_push($s_record['clients'], array(
"id" => $c_record['id'],
"name" => $c_record['name']
));
array_push($result, $s_record);
}
}
}
The remaining problem
This solution doesn't seem to be very efficient.
For each client record I check all sales persons to see if there is a match. I think the number of computations are:
no. of clients * no. of sales persons
I have a huge database and also need to add even more dimensions by mapping projects to the clients and deliverables to the projects. I think this could pose a problem.
Question
Is there a more efficient way to get the same result?
Build an index :
you need to access your salesPerson entries by id, you can start by creating an associative array id => salesPerson, and then use this associative array in your loop.
$salesById = array();
foreach ($salesPersons as $s_record) {
$salesById[ $s_record['id'] ] = $s_record;
}
$result = array();
foreach ($clients as $c_record) {
$s_record = $salesById[ $c_record['salesPersonId'] ];
if ($s_record == null) {
// you may want to handle invalid ids in the client array
// one way is to simply ignore this client record :
continue;
}
array_push($s_record['clients'], array(
"id" => $c_record['id'],
"name" => $c_record['name']
));
array_push($result, $s_record);
}
Notes
There may be a problem in the way you create your $result array :
if a sales person has n clients, the $result array will reference that sales person n times.
Look closer into what result you actually want, you may simply want to return $salesPersons, or $salesById.
As LeGEC said:
you need to access your salesPerson entries by id, you can start by creating an associative array id => salesPerson, and then use this associative array in your loop.
You need to set the index of your arrays with the id:
<?php
$salesPersons = array(
1 => array(
"id" => "1",
"name" => "Mr Smith",
"email" => "mrsmith#email.com",
"clients" => array()
),
2 => array(
"id" => "2",
"name" => "James Bond",
"email" => "jamesbond#email.com",
"clients" => array()
)
);
$clients = array(
1 => array(
"id" => "1",
"name" => "Lucifer Enterprises",
"salesPersonId" => "1"
),
2 => array(
"id" => "2",
"name" => "Charlies Chocolate Factory",
"salesPersonId" => "1"
),
3 => array(
"id" => "3",
"name" => "Geckos Investments",
"salesPersonId" => "2"
),
);
Then:
$result = array();
foreach ($clients as $id => $c_record) {
if (isset($salesPersons[$id])) {
$result[] = array_merge($clients[$id], $salesPersons[$id]);
} else {
$result[] = $clients[$id];
}
}
var_dump($result);
Result here: http://sandbox.onlinephpfunctions.com/code/e590bdb5aaea2794fc5a04ee60f61db766129664
PS:
My code works with your use case, but it will not work if the size of the $salesPersons array is bigger than the $clients array

Appending data in form request laravel inside array

I have a form request which I need to validate . If I dd the $request->all() it shows me the following result.
"adults_information" => array:1 [▼
0 => array:6 [▼
"first_name" => "Luke"
"last_name" => "Greer"
"dob_day" => "08"
"dob_month" => "01"
"dob_year" => 1935
"gender" => "M"
]]
"contact_name" => "Eula Dennis"
"mobile_number" => "7308001726"
What I want is to create extra field after dob_year such as dob which constist of calculation of dob_day,"dob_year","dob_month" . I want some line of code such that when I do dd($request->all()) . I want to get the output like this .
"adults_information" => array:1 [▼
0 => array:6 [▼
"first_name" => "Luke"
"last_name" => "Greer"
"dob_day" => "08"
"dob_month" => "01"
"dob_year" => 1935
"gender" => "M",
"dob"=>"1935-01-08"
]]
"contact_name" => "Eula Dennis"
"mobile_number" => "7308001726"
I tried $request->add() but it didn't work . Any help will be appriciated
The correct syntax is not $request->add but $request->request->add.
So:
$request->request->add([
'adults_information'=>$request->adults_information + ['dob' => '1935-01-08']
]);
$inputs = $request->all();
foreach($inputs['adults_information'] as $key => $info)
{
$dob = $info['dob_year'].'-'.
$info['dob_month'].'-'.
$info['dob_day'];
$inputs['adults_information'][$key]['dob'] = $dob;
}
$request->merge($inputs);
dd($request->all());
Hi u can use merge() with array_push to push a nested array.
$adults_information = $request->adults_information;
$insert = [
"first_name" => "Luke",
"last_name" => "Greer",
"dob_day" => "08",
"dob_month" => "01",
"dob_year" => 1935,
"gender" => "M",
"dob"=>"1935-01-08"
];
array_push($adults_information, $insert);
$request->merge('adults_information', $adults_information);
https://laravel.com/docs/5.6/requests
Hope this helps
You can use replace method for appending item to request object. For more details you can check Laravel API docs https://laravel.com/api/5.6/Illuminate/Http/Request.html#method_replace . For example.
$data = $request->all();
$data['appending_data_1'] = 'dummy value';
$data['appending_data_2'] = 'dummy value';
$request->replace($data);

json_encode, associative array needed in [ brackets ]

I'm using PHP, and in order to feed some data to an API using Curl, I need to format some strings and have been using json_encode. It works just fine for simpler bits, but this I can't figure out:
The API expects this:
{
"id": "string",
"startTime": "2017-04-18T08:04:23.167Z",
"endTime": "2017-04-18T08:04:23.167Z",
"contacts": [
{
"id": "string",
"displayName": "string"
}
My code so far:
$data_set_pre = array(
"id" => "",
"startTime" => "2017-04-14T07:47:59.028Z",
"endTime" => "2017-04-15T07:47:59.028Z",
"contacts" => array("id" => "ahashofsomenumbersandletters", "displayName" => "John Doe"),
);
$data_set = json_encode($data_set_pre);
Unfortunately, this produces:
{"id":"","startTime":"2017-04-14T07:47:59.028Z","endTime":"2017-04-15T07:47:59.028Z","contacts":{"id":"ahashofsomenumbersandletters","displayName":"John Doe"}}
I've been researching, and I'm getting the impression that json_encode will encode everything BUT an unbroken sequential array starting from 0 as an object, and I don't now how to work around this.
(No, I can't change what the API requires, it's provided by a 3rd-party).
<?php
$data_set_pre = array(
"id" => "12",
"startTime" => "2017-04-14T07:47:59.028Z",
"endTime" => "2017-04-15T07:47:59.028Z",
"contacts" => array(
array(
"id" => "ahashofsomenumbersandletters", "displayName" => "John Doe"
)
)
);
$data_set = json_encode($data_set_pre);
Change the following line:
"contacts" => array("id" => "ahashofsomenumbersandletters", "displayName" => "John Doe"),
to
"contacts" => array(array("id" => "ahashofsomenumbersandletters", "displayName" => "John Doe")),
It will give:
{"id":"","startTime":"2017-04-14T07:47:59.028Z","endTime":"2017-04-15T07:47:59.028Z","contacts":[{"id":"ahashofsomenumbersandletters","displayName":"John Doe"}]}
here [{"id":"ahashofsomenumbersandletters","displayName":"John Doe"}] is a multi-dimension array

PHP Json response formatting

I have the following script that returns a json response.
$response["customer_creds"] =array(array('customer_names'=>$user['name'], 'customer_email' => $user['email'], 'customer_id' => $user['customer_id'], 'customer_type' => $user['customer_type'], 'rating' => $user['rating']));
The above script returns:
"customer_creds": [
{
"customer_names": "John Doe",
"customer_email": "example#example.com",
"customer_id": "123456",
"customer_type": "1",
"rating": "4"
}
],
Now I want my json to return the customer_type as an object.("customer_type": [1],
I have tried json decoding and encoding on the same script but nothing seems to work. Any workarounds on this? At a later stage I'll want to have my json to return multiple customer types. The final response should be something like this:
"customer_creds": [
{
"customer_names": "John Doe",
"customer_email": "example#example.com",
"customer_id": "123456",
"customer_type": [1,2,3],
"rating": "4"
}
],
Any suggestion would be highly appreciated. Thanks
You just want the customer_type to be an array of values, instead of just one value?
$response["customer_creds"] = array(
array(
'customer_names' => $user['name'],
'customer_email' => $user['email'],
'customer_id' => $user['customer_id'],
'customer_type' => array($user['customer_type']), // Just wrap it with array()
'rating' => $user['rating']
)
);

Categories